Sub topic 15
Getting changed rows back with RETURNING
This chapter assumes you can write basic INSERT, UPDATE, and DELETE statements, that you understand primary keys and foreign keys, and that you know what a transaction is. It uses the customers and orders tables from earlier in the tutorial.
The problem RETURNING solves
A plain data-changing statement reports only a count, such as DELETE 3 or "3 rows affected". It does not tell you which rows changed or what their values are afterward. If you need that information, the usual workaround is a second query:
- Run a
SELECTto find the rows. - Run the
DELETEorUPDATE.
Between those two steps another session can change the data, so the rows you looked at may not be the rows you changed. Two statements also mean two round trips to the database.
RETURNING fixes this. You add it to the end of an INSERT, UPDATE, or DELETE, and the statement sends back a result set, like a SELECT, with one row for each row it changed. The rows come from the same statement that made the change, so nothing can slip in between.
Basic syntax
You list the columns or expressions you want after the keyword RETURNING. Use * for every column.
DELETE FROM orders
WHERE status = 'cancelled'
RETURNING id, customer_id;The statement deletes every cancelled order and sends back the id and customer_id of each deleted row. The deletion happens exactly as it would without RETURNING. The clause only adds output.
If the WHERE clause matches no rows, the statement succeeds and returns an empty result set. That is not an error.
What each statement returns
The meaning of "the row" depends on the statement.
| Statement | Rows returned | Column values shown |
|---|---|---|
| `INSERT` | Each row that was inserted | The values as stored, including defaults and generated values |
| `UPDATE` | Each row that was updated | The values after the update |
| `DELETE` | Each row that was deleted | The values the row had before it was removed |
Rows that the statement does not touch are never returned. An UPDATE whose WHERE clause skips a row will not list that row.
INSERT: reading back generated values
The most common use is learning a value the database created for you. In earlier examples we supplied id ourselves. In practice the key is often generated by an identity column or a sequence, and you do not know it until the row exists. The status column also receives a default you did not write.
INSERT INTO customers (id, name, email)
VALUES (4, 'Edsger Dijkstra', '[email protected]')
RETURNING id, status;The result contains the id you supplied and the status active, which came from the column default. With a generated key, the same pattern returns the new key in one step, so you do not need a follow-up query such as SELECT MAX(id). That follow-up query is unsafe when several sessions insert at once.
RETURNING also works with multi-row inserts. You get one result row for each inserted row:
INSERT INTO customers (id, name, email)
VALUES
(5, 'Barbara Liskov', '[email protected]'),
(6, 'Donald Knuth', '[email protected]')
RETURNING id, name;UPDATE: seeing the new values
For an UPDATE, RETURNING shows the row after the change. This is useful when the new value is computed, because you can read the result without calculating it again in your application.
UPDATE orders
SET total = total * 1.10,
status = 'repriced'
WHERE status = 'new'
RETURNING id, total, status;The returned total is the new, increased amount. If you also need the old amount, standard RETURNING cannot give it to you. Preview the rows with a SELECT first, or read the old values in the same transaction before the update. Recent PostgreSQL releases (version 18 and later) let you refer to old and new values in RETURNING, but older versions and other dialects do not.
DELETE: keeping a record of what was removed
For a DELETE, the returned values are the ones the row had before removal. This lets you log or archive what you deleted without a separate query.
DELETE FROM orders
WHERE status = 'cancelled'
RETURNING id, customer_id, total;You can go one step further and move rows between tables in a single statement. PostgreSQL allows a data-changing statement inside a common table expression (WITH), so the deleted rows can feed an INSERT:
CREATE TABLE orders_archive (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
total NUMERIC(10, 2) NOT NULL
);
WITH removed AS (
DELETE FROM orders
WHERE status = 'cancelled'
RETURNING id, customer_id, total
)
INSERT INTO orders_archive (id, customer_id, total)
SELECT id, customer_id, total
FROM removed;Either both steps happen or neither does, because they are one statement. SQLite does not allow DELETE inside a WITH clause, so this form is PostgreSQL-specific among the dialects in this tutorial.
Expressions and aliases
RETURNING accepts expressions and aliases, not only column names:
UPDATE orders
SET total = total * 1.10
WHERE id = 100
RETURNING id, total AS new_total, total > 100 AS is_large;Each returned column behaves like a column in a SELECT list. You can compute values and rename them. You cannot use aggregate functions such as SUM, and you cannot reference other tables in the list (PostgreSQL allows columns from tables named in FROM or USING, but not arbitrary subquery joins in all dialects).
RETURNING and constraints
RETURNING does not change whether a statement succeeds. If a constraint rejects the change, the statement fails as usual and returns no rows. For example, this insert violates the foreign key on orders.customer_id:
INSERT INTO orders (id, customer_id, total)
VALUES (101, 999, 25.00)
RETURNING id;The database raises a foreign key error and the statement changes nothing. Do not assume that rows returned by a statement are permanent. They are only permanent once the surrounding transaction commits:
BEGIN;
DELETE FROM orders
WHERE status = 'cancelled'
RETURNING id;
ROLLBACK;The DELETE reports the removed ids, but ROLLBACK then restores every row. Treat returned rows as a report of what the statement did inside your transaction.
Combining RETURNING with upsert
RETURNING pairs well with the upsert pattern from the next chapter. In PostgreSQL and SQLite, you can see which row ended up in the table whether it was inserted or updated:
INSERT INTO customers (id, name, email)
VALUES (1, 'Ada King', '[email protected]')
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name
RETURNING id, name;One edge case matters here. If the conflict clause is DO NOTHING, a conflicting row is skipped and is not returned. The result set then has fewer rows than you tried to insert. Code that expects one returned row for each input row must check for that.
SQL Server: the OUTPUT clause
SQL Server offers the same capability with OUTPUT. It sits in the middle of the statement, before WHERE or VALUES, and you name the old or new values explicitly with the pseudo-tables inserted and deleted:
DELETE FROM orders
OUTPUT deleted.id, deleted.customer_id
WHERE status = 'cancelled';
UPDATE orders
SET total = total * 1.10
OUTPUT deleted.total AS old_total, inserted.total AS new_total
WHERE status = 'new';Here deleted holds the row as it was before the change and inserted holds it afterward. This makes OUTPUT more flexible than standard RETURNING, because an UPDATE can report both the old and the new value.
Dialect summary
| Dialect | Syntax | Notes |
|---|---|---|
| PostgreSQL | `RETURNING` | Works on INSERT, UPDATE, DELETE. Allowed inside `WITH`. |
| SQLite 3.35+ | `RETURNING` | Not allowed with `DELETE` inside `WITH`. |
| MariaDB | `RETURNING` | Supported on INSERT and DELETE. |
| SQL Server | `OUTPUT` | Offers `inserted` and `deleted` for old and new values. |
| MySQL | None | Run a `SELECT` afterward, or use `LAST_INSERT_ID()` for a generated key. |
Common mistakes
- Expecting RETURNING to exist everywhere. On MySQL the statement is a syntax error. Write a version for each dialect your project supports.
- Reading old values from an UPDATE. Plain
RETURNINGshows the new values. - Treating returned rows as committed. A later
ROLLBACKdiscards the change, even though you already received the rows. - Forgetting that no match means no rows. Always handle an empty result set in application code.
- Using RETURNING as a substitute for a preview. It reports what happened after the change. To check what a statement will touch before you run it, preview with a
SELECTfirst, as described earlier in the tutorial.
Exercise
You run UPDATE orders SET status = 'shipped' WHERE id = 100 RETURNING id, status; on PostgreSQL, and no order with id 100 exists. What does the database return, and is it an error? Then write a single PostgreSQL statement that deletes all orders with status 'cancelled' and returns only each deleted order's id and total.
Show answer
The statement succeeds and returns an empty result set (zero rows). Matching no rows is not an error. The second statement is: DELETE FROM orders WHERE status = 'cancelled' RETURNING id, total; The returned values are those the rows had before deletion.
Exercise
On SQL Server, rewrite this UPDATE so it reports both the old and the new total for every changed row: UPDATE orders SET total = total * 1.10 WHERE status = 'new';
Show answer
UPDATE orders SET total = total * 1.10 OUTPUT deleted.total AS oldtotal, inserted.total AS newtotal WHERE status = 'new'; The deleted pseudo-table holds the row before the change and inserted holds it after.