Sub topic 13
Edge cases and common mistakes
This chapter assumes you know the basic forms of INSERT, UPDATE, DELETE ... RETURNING and can run statements in psql or another client. It also assumes you have seen ON CONFLICT, data-modifying CTEs and triggers in earlier chapters. All examples use the tasks table from earlier in the tutorial.
Most RETURNING bugs come from wrong assumptions about what a statement hands back and when. Each section below names one assumption and shows what happens instead.
Zero rows is a normal result
RETURNING produces one row per row the statement affected. If the WHERE clause matches nothing, the result has zero rows. PostgreSQL does not raise an error.
UPDATE tasks
SET status = 'done'
WHERE title = 'No such task'
RETURNING id, status;psql prints an empty result and the status UPDATE 0. Application code that calls "fetch one row" and assumes it succeeds will fail on this case. Treat an empty result as "nothing matched", and decide whether that is an error in your program, not in the database.
The same applies to DELETE. A BEFORE row trigger that returns NULL also skips the row, so that row produces no output.
Returned values are not committed values
RETURNING gives you values from inside the current transaction. If the transaction rolls back later, the row never existed, and the identity value you received is gone. The sequence behind an identity column does not roll back, so the number is not reused either.
BEGIN;
INSERT INTO tasks (title) VALUES ('Temporary') RETURNING id;
ROLLBACK;Do not hand the returned id to another system, such as a queue, an email or a cache, until the transaction commits. Otherwise that system refers to a row that does not exist.
ON CONFLICT: which path returns a row
With ON CONFLICT DO UPDATE, a row comes back from either path. With DO NOTHING, a conflicting row is skipped and produces no output row.
A common fix is to write a no-op update, such as SET title = EXCLUDED.title. It works, but it has a cost. The no-op still writes a new row version, so it adds dead tuples that VACUUM must clean up. It also fires UPDATE triggers. If you only want the existing row's id, a fallback SELECT avoids both costs:
WITH ins AS (
INSERT INTO tasks (title)
VALUES ('Review PR')
ON CONFLICT (title) DO NOTHING
RETURNING id, title
)
SELECT id, title FROM ins
UNION ALL
SELECT id, title FROM tasks
WHERE title = 'Review PR'
AND NOT EXISTS (SELECT 1 FROM ins);This has a race. Suppose another transaction inserts 'Review PR' and commits after your statement's snapshot was taken but before your insert resolves its conflict. Your DO NOTHING fires, but the fallback SELECT uses the older snapshot and cannot see the row. The result is empty. If you need a guaranteed answer, use the no-op DO UPDATE form, or retry the statement.
Another limit: a single INSERT ... ON CONFLICT DO UPDATE cannot touch the same row twice. If two rows in your VALUES list conflict with the same existing row, PostgreSQL raises the error "ON CONFLICT DO UPDATE command cannot affect row a second time". Remove duplicate keys from the input first.
UPDATE returns the new row, not the old one
UPDATE ... RETURNING shows values after the change. People often want the previous value, for example to log a status transition. On PostgreSQL 18 and later you can use old.status. On earlier versions, join the target to a locked copy of itself:
UPDATE tasks AS t
SET status = 'done'
FROM (
SELECT id, status
FROM tasks
WHERE id = 1
FOR UPDATE
) AS prev
WHERE t.id = prev.id
RETURNING prev.status AS previous_status, t.status AS current_status;The FOR UPDATE lock keeps another session from changing the row between the read and the write. Without it, previous_status can be stale under concurrency.
On PostgreSQL 18, RETURNING old.* and new.* are NULL where no such version exists. For an INSERT, old is NULL. For a DELETE, new is NULL. If a table is itself named old or new, rename the references with RETURNING WITH (OLD AS o, NEW AS n).
Triggers: BEFORE changes show up, AFTER changes do not
RETURNING reports the row as it was stored by the statement. A BEFORE row trigger can modify NEW, and the modification appears in the result.
CREATE FUNCTION tasks_trim_title() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.title := btrim(NEW.title);
RETURN NEW;
END
$$;
CREATE TRIGGER tasks_trim
BEFORE INSERT OR UPDATE ON tasks
FOR EACH ROW EXECUTE FUNCTION tasks_trim_title();
INSERT INTO tasks (title) VALUES (' Plan sprint ')
RETURNING id, title;The returned title is Plan sprint, without the spaces. An AFTER trigger that later updates the same row, or that changes other tables, does not change what this statement returns. If an AFTER trigger sets a column, run a separate SELECT after the statement, or move the logic into a BEFORE trigger.
On views, RETURNING works on simple auto-updatable views. If you use INSTEAD OF triggers, the trigger function must return the row it wants reported, usually NEW. Returning NULL makes the statement report nothing.
Data-modifying CTEs do not see each other's changes
In a WITH query, every sub-statement and the main query use the same snapshot. The main query cannot see rows that a data-modifying CTE wrote to the table. The only way to pass those rows along is through RETURNING.
WITH ins AS (
INSERT INTO tasks (title) VALUES ('Plan sprint 2') RETURNING id
)
SELECT
(SELECT count(*) FROM tasks WHERE title = 'Plan sprint 2') AS seen_in_table,
(SELECT count(*) FROM ins) AS seen_in_returning;The result is seen_in_table = 0 and seen_in_returning = 1. Two further rules apply:
- A data-modifying CTE always runs to completion, even if the main query never reads its output.
- The order in which separate data-modifying CTEs run is not specified. Do not rely on one happening before another. If two of them try to change the same row, only one takes effect, and you cannot predict which.
Row order and mapping results to input
A multi-row INSERT ... VALUES ... RETURNING usually returns rows in input order, but the documentation does not guarantee it. Do not map results to inputs by position. Return a natural key, such as title, and match on that:
INSERT INTO tasks (title)
VALUES ('Draft spec'), ('Write tests')
RETURNING title, id;RETURNING has no ORDER BY. If order matters, put the statement in a CTE and sort in the outer SELECT.
Other limits worth knowing
- No aggregates or window functions.
RETURNING count(*)is an error. Wrap the statement in a CTE and aggregate in the outer query:WITH d AS (DELETE ... RETURNING 1) SELECT count(*) FROM d. RETURNING *is fragile. Adding or reordering columns changes what your code receives, and wide or TOASTed columns add transfer cost. Name the columns you use.DELETEhas noLIMIT. To take a few rows, select their keys in a subquery. The next statement claims one open task and returns it, andSKIP LOCKEDlets concurrent workers claim different rows:
DELETE FROM tasks
WHERE id IN (
SELECT id
FROM tasks
WHERE status = 'open'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED
)
RETURNING id, title;- Version limits.
MERGE ... RETURNINGandmerge_action()need PostgreSQL 17 or later.oldandnewinRETURNINGneed 18 or later. On older servers these forms give a syntax error, not a different result. - Drivers separate the row count from the rows. The "rows affected" number and the returned rows are different things. In most drivers you must call the query method that returns rows. A call that only reports a count discards your data.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Empty result from `UPDATE ... RETURNING` | `WHERE` matched no rows | Handle zero rows in code |
| No row after `ON CONFLICT DO NOTHING` | Conflicting row is skipped | Use no-op `DO UPDATE` or a fallback `SELECT` |
| Old value missing | `UPDATE` returns the new row | Use `old.` on 18+, or join a locked copy |
| Trigger edit missing | Edit made in an `AFTER` trigger | Use a `BEFORE` trigger or re-select |
| Main query misses CTE writes | Shared snapshot | Read `RETURNING` output from the CTE |
| Wrong id matched to input | Relied on row order | Return and match on a unique key |
| Syntax error near `merge_action` or `old` | Server version too old | Check `SHOW server_version` |
Exercise
Why can INSERT ... ON CONFLICT (title) DO NOTHING RETURNING id return zero rows even though a row with that title exists, and what are two ways to get the existing id?
Show answer
With DO NOTHING, a conflicting row is skipped, so the statement affects no row and RETURNING has nothing to output. One fix is DO UPDATE SET title = EXCLUDED.title, which touches the row and returns it, at the cost of a new row version and any UPDATE triggers. The other is a CTE that falls back to a SELECT on the table when the insert returned nothing. That fallback can miss a row committed by a concurrent transaction after the statement's snapshot, so retry if you need certainty.
Exercise
On PostgreSQL 16, write an UPDATE that sets status to 'done' for id 1 and returns both the previous and the new status.
Show answer
UPDATE tasks AS t SET status = 'done' FROM (SELECT id, status FROM tasks WHERE id = 1 FOR UPDATE) AS prev WHERE t.id = prev.id RETURNING prev.status AS previousstatus, t.status AS currentstatus; The FOR UPDATE lock stops another session from changing the row between the read and the write.