Sub topic 8
Reading results with RETURNING
This chapter covers how to read back the rows an upsert produced. It assumes you can run SELECT, INSERT, and UPDATE in psql, that you know what a primary key and a unique constraint are, and that you have seen ON CONFLICT DO NOTHING and ON CONFLICT DO UPDATE with the EXCLUDED row. The examples use the product_stock table from earlier chapters.
Why an upsert needs RETURNING
An upsert either inserts a row or changes an existing one. The calling application often needs to know the final state of the row. It may need a generated id, a default such as updated_at, or the value after a calculation like product_stock.quantity + EXCLUDED.quantity.
Without RETURNING, you would run a second SELECT after the upsert. That costs a round trip. It also opens a small window in which another session can change the row between your two statements. RETURNING hands back the row from the same statement, so the values you read are the ones that statement wrote.
RETURNING is not specific to upserts. It works on INSERT, UPDATE, DELETE, and MERGE (in PostgreSQL 17 and later). With ON CONFLICT it has one rule that surprises people, covered below.
Setting up the example table
Start from a clean table so the outputs below match what you see.
DROP TABLE IF EXISTS product_stock;
CREATE TABLE product_stock (
sku text PRIMARY KEY,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);RETURNING on a plain insert
Add a RETURNING clause at the end of the statement. It takes a list of expressions, just like a SELECT list.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
RETURNING sku, quantity, updated_at;The result is one row with the values as stored, including the updated_at default that you did not supply. Use RETURNING * to get every column. In application code, naming the columns is safer, because * changes shape when someone adds a column.
RETURNING with DO UPDATE
When the conflict path runs DO UPDATE, the returned row is the row after the update. When there is no conflict, it is the row after the insert. Both paths produce one output row, so the client reads the same shape either way.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity,
updated_at = now()
RETURNING sku, quantity, updated_at;If A-100 already held 5, the result shows quantity = 8. You get the combined value without a second query.
The rule that surprises people: skipped rows are not returned
RETURNING only reports rows that the statement actually inserted or updated. A row that the statement skipped produces no output at all. This happens in two cases:
DO NOTHINGfound a conflict and skipped the row.DO UPDATE ... WHERE conditionfound a conflict, but the condition was false, so the update did not run.
Try the first case.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO NOTHING
RETURNING sku, quantity;If A-100 exists, this returns zero rows. The statement succeeds, and the result set is empty. Code that does rows[0] without checking will fail with an index error or a null dereference.
The second case works the same way.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now()
WHERE product_stock.quantity IS DISTINCT FROM EXCLUDED.quantity
RETURNING sku, quantity;If the stored quantity is already 5, the WHERE clause is false, the row is left untouched, and nothing is returned. If the quantity differs, the row is updated and returned.
The following diagram shows which rows produce output.
Telling an insert from an update
Often you need to know whether the row was new or existing. Counting on a separate query is unreliable. A common trick uses the system column xmax.
INSERT INTO product_stock (sku, quantity)
VALUES ('C-300', 7)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now()
RETURNING sku, quantity, (xmax = 0) AS inserted;For a freshly inserted row, xmax is 0, so inserted is true. For an updated row, xmax holds the transaction id that locked or replaced the previous version, so inserted is false. Run the statement twice and compare the two outputs.
An alternative that stays within documented behavior is to compare timestamps you control. For example, if you set created_at only on insert and updated_at on every write, a row where the two are equal was just created.
Returning values from the old row
RETURNING in an upsert sees the new version of the row. It does not give you the value the row held before the update. Before PostgreSQL 18, there is no OLD reference in RETURNING. If you need the previous value, you have two options.
- Read it first with
SELECT ... FOR UPDATEin the same transaction, then run the upsert. - Compute it from what you know. For an additive update, the old quantity is the returned quantity minus the proposed quantity.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity
RETURNING sku,
quantity AS new_quantity,
quantity - 3 AS previous_quantity;The second option is only valid when the update is a simple addition and the row existed. For a fresh insert, quantity - 3 gives 0, which happens to be a sensible "previous" value here but is not a real stored value.
Using RETURNING inside a larger query
A data-modifying statement with RETURNING can sit inside a common table expression (CTE), which is a named subquery introduced by WITH. The outer query then reads the returned rows like a table. This lets you chain work in a single statement.
WITH upserted AS (
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 3), ('D-400', 9)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity,
updated_at = now()
RETURNING sku, quantity
)
SELECT sku, quantity, quantity < 10 AS low_stock
FROM upserted
ORDER BY sku;PostgreSQL executes the data-modifying CTE exactly once, whether or not the outer query reads all of its rows. Only the rows that the upsert inserted or updated appear in upserted. Skipped rows are absent here too.
Getting a row back even when it is skipped
Sometimes you want the id of a row whether it was newly created or already there. This is common for lookup tables, where you insert a name and need its id. DO NOTHING ... RETURNING fails you here because an existing row returns nothing. Consider this table.
CREATE TABLE tag (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE
);There are two common solutions.
The first is a no-op DO UPDATE. Setting a column to its own value forces the row to count as updated, so it is returned.
INSERT INTO tag (name)
VALUES ('postgres')
ON CONFLICT (name) DO UPDATE
SET name = EXCLUDED.name
RETURNING id, name;This is simple and always returns a row. The cost is that every conflict writes a new row version, which creates a dead tuple (an obsolete row version that vacuum must later clean up) and fires update triggers. On a hot table that adds write load for no change in data.
The second is to combine the insert with a fallback SELECT in a CTE.
WITH ins AS (
INSERT INTO tag (name)
VALUES ('postgres')
ON CONFLICT (name) DO NOTHING
RETURNING id, name
)
SELECT id, name FROM ins
UNION ALL
SELECT id, name FROM tag WHERE name = 'postgres'
LIMIT 1;If the insert happened, ins supplies the row, and LIMIT 1 stops before the second branch matters. If the insert was skipped, the SELECT finds the existing row. This avoids needless writes. It has a narrow race: if another transaction inserted the same name but has not yet committed when this statement takes its snapshot, the insert waits for that transaction, then skips, and the fallback SELECT may not see the row because it uses the older snapshot. In that case the query returns nothing. For strict correctness under heavy concurrency, either use the no-op DO UPDATE or retry the statement when it returns no row.
| Approach | Always returns a row | Writes on conflict | Notes |
|---|---|---|---|
| `DO NOTHING ... RETURNING` | No | No | Existing rows return nothing |
| No-op `DO UPDATE ... RETURNING` | Yes | Yes | Dead tuples and triggers |
| `DO NOTHING` plus fallback `SELECT` | Almost always | No | Rare empty result under concurrency; retry |
RETURNING with batch upserts
With several rows in one statement, RETURNING produces one output row per row inserted or updated. The order of the output is not guaranteed to match the order of your VALUES list. Do not match results to inputs by position. Return the key and match on it.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 1), ('E-500', 2), ('F-600', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity
WHERE product_stock.quantity <> EXCLUDED.quantity
RETURNING sku, quantity;Combine this with a WHERE clause and the output contains only the rows that changed or were created. That makes it a cheap way to report what a batch actually did. To count the affected rows, a client driver usually exposes the command tag, such as INSERT 0 2. The final number is the count of rows inserted or updated, which excludes skipped rows. It matches the number of rows RETURNING produces.
Common errors
- Reading
rows[0]without a check. WithDO NOTHINGor a conditional update, the result can be empty. - Using
RETURNINGcolumns that do not exist.EXCLUDEDis not available inRETURNING. Return table columns only, and compute any comparison from them. - Assuming result order equals input order. Match by key.
- Treating the
xmaxtrick as a guarantee. It is an implementation detail. - Expecting the old value. Without
OLDsupport,RETURNINGshows the new row.
Exercise
A table counter(name text PRIMARY KEY, hits integer NOT NULL) holds a row ('home', 10). You run INSERT INTO counter (name, hits) VALUES ('home', 1) ON CONFLICT (name) DO NOTHING RETURNING hits;. What does the statement return, and how would you change it so the caller always gets the current hits value, increasing it by 1 when the row exists?
Show answer
It returns zero rows. The conflict makes DO NOTHING skip the row, and RETURNING reports only inserted or updated rows. Change it to INSERT INTO counter (name, hits) VALUES ('home', 1) ON CONFLICT (name) DO UPDATE SET hits = counter.hits + EXCLUDED.hits RETURNING hits;. It returns 11 for the existing row, or 1 if the row did not exist.
Exercise
You run a batch upsert with ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity WHERE product_stock.quantity IS DISTINCT FROM EXCLUDED.quantity RETURNING sku and send 100 rows. It returns 12 rows. What can you conclude, and what can you not conclude about the other 88?
Show answer
Twelve rows were inserted or changed. The other 88 were either conflicts with an unchanged quantity, which the WHERE clause skipped, or are otherwise not reported. You cannot tell from the output alone which input rows they were, and you cannot tell that they exist, only that they were not written. To list them, compare the returned keys against your input keys.