Sub topic 10
Seeing what changed with RETURNING
This chapter assumes you can write UPDATE ... FROM and DELETE ... USING statements and read a basic INNER JOIN. It also assumes you can run statements in psql. The examples use the customers, orders, products, and price_updates tables from earlier in this tutorial.
A join-based change can touch many rows, and the command tag (UPDATE 2, DELETE 5) only gives a count. The RETURNING clause makes the statement return the affected rows, as a SELECT would. You can use it to check a change, to log it, or to pass the rows to another statement.
What RETURNING does
RETURNING goes at the end of an INSERT, UPDATE, or DELETE. It takes a list of expressions, like a SELECT list. PostgreSQL evaluates the list once for each row the statement actually modified.
- For
UPDATE, the target table's columns hold the new values, afterSEThas been applied. - For
DELETE, the columns hold the values of the row that was removed. - Rows that the join or
WHEREclause did not select produce no output. - If no rows match, the statement returns zero rows and the command tag reads
UPDATE 0orDELETE 0.
Sample data
The examples below need a few rows. Run this on freshly created tables.
INSERT INTO products (id, name, price) VALUES
(1, 'Keyboard', 40.00),
(2, 'Mouse', 20.00),
(3, 'Monitor', 150.00);
INSERT INTO price_updates (product_id, new_price) VALUES
(1, 45.00),
(2, 18.50);
INSERT INTO customers (id, name, status) VALUES
(1, 'Ana', 'active'),
(2, 'Ben', 'closed');
INSERT INTO orders (id, customer_id, total, status) VALUES
(10, 1, 30.00, 'open'),
(11, 2, 55.00, 'open'),
(12, 2, 12.50, 'paid');RETURNING with UPDATE ... FROM
Each example runs inside a transaction that ends with ROLLBACK, so you can repeat it on the same data.
BEGIN;
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id
RETURNING p.id, p.name, p.price;
ROLLBACK;The result has one row for each product that received a new price:
| id | name | price |
|---|---|---|
| 1 | Keyboard | 45.00 |
| 2 | Mouse | 18.50 |
The Monitor does not appear because no staging row matched it. A missing row in the output is the quickest way to spot a product that your join skipped.
The order of rows is not guaranteed. If a client needs a stable order, collect the rows and sort them there. Alternatively, wrap the statement in a CTE and sort in the outer query (see the later chapter on data-modifying CTEs).
Columns from the other tables
In UPDATE ... FROM and DELETE ... USING, the RETURNING list can use columns from the joined tables as well as from the target. This works because the joined row is available while the statement runs.
BEGIN;
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
RETURNING o.id AS order_id, o.total, c.name AS customer_name;
ROLLBACK;| order_id | total | customer_name |
|---|---|---|
| 11 | 55.00 | Ben |
| 12 | 12.50 | Ben |
Here the output tells you which orders were removed and why: they belonged to the closed customer Ben. A plain DELETE followed by a SELECT could not show this, because the rows are already gone.
Watch out for RETURNING *
RETURNING * returns every column of the target table, and with FROM or USING it also returns every column of the joined tables. The output is wider than you probably expect, and duplicate column names such as id become ambiguous for client code. Qualify the star with the target alias:
BEGIN;
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id
RETURNING p.*;
ROLLBACK;Showing old and new values together
RETURNING on an UPDATE shows the new values. For an audit trail you often want the old price next to the new one. In PostgreSQL 18 and later, you can write RETURNING old.price, new.price. On earlier versions, join the target table a second time under another alias. That second reference reads the table as it was when the statement began, so it sees the old values.
BEGIN;
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u, products AS prev
WHERE u.product_id = p.id
AND prev.id = p.id
RETURNING p.id, p.name, prev.price AS old_price, p.price AS new_price;
ROLLBACK;| id | name | old_price | new_price |
|---|---|---|---|
| 1 | Keyboard | 40.00 | 45.00 |
| 2 | Mouse | 20.00 | 18.50 |
The alias prev is a read-only second view of products. It is joined by primary key, so each target row matches exactly one prev row and the row count does not change. Do not use old as the alias name. PostgreSQL 18 reserves old and new inside RETURNING.
Details that affect what you see
- One result row per modified target row. If several joined rows match one target row, PostgreSQL still updates that row once, and
RETURNINGproduces one row for it. You cannot see the matches that were ignored, so use aSELECTwith the same join to look for duplicates before you run the update. - Before triggers are visible, after triggers are not. A
BEFOREtrigger can change the row, andRETURNINGreports the changed row. AnAFTERtrigger runs later, and its changes do not appear. - The rows are returned even if you roll back.
RETURNINGreports what the statement did. If you then runROLLBACK, the database discards those changes, but the output you already saw remains on screen. Treat it as a preview, not a record of committed data. - No aggregates. You cannot write
RETURNING count(*). To count affected rows, use a data-modifying CTE and aggregate in the outer query, or read the count from the command tag. - Expressions are allowed. You can compute values, for example
RETURNING p.price - prev.price AS change, and you can call functions. - Row-level security and permissions apply. To return a column, the role needs
SELECTprivilege on it, in addition to the privilege for the modification.
Using RETURNING as a safety check
RETURNING is useful in the preview workflow covered in the next chapters:
- Open a transaction with
BEGIN. - Run the
UPDATEorDELETEwith aRETURNINGlist that identifies each row. - Compare the returned rows with what you expected: the right count, the right keys, no surprises.
- Run
COMMITif the output is right andROLLBACKif it is not.
In psql, the command tag after the rows (UPDATE 2) gives the count. A count much larger than your expectation is a strong sign of a join mistake. In an application, the driver usually returns the rows as a normal result set, so you can use the same statement without a second query.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `RETURNING *` with `FROM` or `USING` | Extra columns, ambiguous names | Use `p.*` or list columns |
| Expecting old values from `RETURNING` on an `UPDATE` | You get the new values | Join a second alias of the target (or use `old.` on PostgreSQL 18+) |
| Using the output as proof of a commit | Rows appear even when you later roll back | Check that `COMMIT` succeeded |
| Reading a short result as "nothing wrong" | Rows that did not join are silently absent | Compare the count with a `SELECT` of the intended rows |
Exercise
You run DELETE FROM orders AS o USING customers AS c WHERE o.customer_id = c.id AND c.status = 'closed' RETURNING o.id, c.name; inside a transaction. It returns 2 rows. You then run ROLLBACK. How many of those orders are still in the table, and why can the output still be useful?
Show answer
Both orders are still in the table, because ROLLBACK undoes the delete. The output is still useful as a preview: it showed exactly which orders (and which customer names) the statement would have removed, so you could confirm the join before running the same statement again with COMMIT.
Exercise
Write an UPDATE ... FROM that sets each product's price from priceupdates (matching on productid) and returns the product id, its price before the change, and its price after, on a PostgreSQL version earlier than 18.
Show answer
UPDATE products AS p SET price = u.newprice FROM priceupdates AS u, products AS prev WHERE u.productid = p.id AND prev.id = p.id RETURNING p.id, prev.price AS oldprice, p.price AS new_price; The second alias prev reads the table as it was before the statement, so it holds the old price.