Sub topic 8
RETURNING with ON CONFLICT: what comes back and what does not
This chapter assumes you can write basic INSERT ... ON CONFLICT statements and know how RETURNING works on plain INSERT, UPDATE and DELETE. It also assumes you can run SQL in psql or another PostgreSQL client. The examples use the tasks table from earlier chapters. The MERGE example needs PostgreSQL 17 or later.
An upsert, meaning INSERT ... ON CONFLICT, can take one of several paths for each input row. RETURNING reports only some of those paths, and the rule is not the same for every conflict action. If you assume every input row produces an output row, you will eventually lose data or hit a null in application code.
Setup
Run this to get a known starting state:
DROP TABLE IF EXISTS tasks;
CREATE TABLE tasks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL UNIQUE,
status text NOT NULL DEFAULT 'open',
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO tasks (title)
VALUES ('Write report'), ('Review PR');The UNIQUE constraint on title is what ON CONFLICT (title) uses to detect duplicates.
The core rule
RETURNING in an upsert returns one row for each row that the statement actually inserted or updated. It returns nothing for an input row that was skipped.
The conflict action decides which rows are skipped:
| Conflict action | Input row has no conflict | Input row conflicts |
|---|---|---|
| `DO NOTHING` | Inserted and returned | Skipped, not returned |
| `DO UPDATE` | Inserted and returned | Updated and returned (the new version of the row) |
| `DO UPDATE ... WHERE cond` | Inserted and returned | Updated and returned if `cond` is true. Otherwise skipped and not returned |
DO NOTHING: conflicting rows vanish from the output
Insert two rows, one of which already exists:
INSERT INTO tasks (title)
VALUES ('Review PR'), ('Plan sprint')
ON CONFLICT (title) DO NOTHING
RETURNING id, title;The result contains one row, for Plan sprint. Review PR already existed, so PostgreSQL skipped it and RETURNING has nothing to say about it. The statement succeeds either way.
This is useful when you only want to act on rows that are new. For example, you might send a welcome email only for the rows that came back. It is a problem when you wanted the id of every title, because the existing ones are missing from the output.
Note that the skipped row still consumed an identity value. PostgreSQL calls the sequence before it checks for a conflict, so repeated conflicting upserts leave gaps in id. Gaps are normal, and you should not build logic that expects consecutive ids.
DO UPDATE: both paths return a row
To get a row back in both cases, make the conflict path do an update:
INSERT INTO tasks (title)
VALUES ('Review PR'), ('Ship release')
ON CONFLICT (title) DO UPDATE
SET updated_at = now()
RETURNING id, title, updated_at;Both input rows appear in the output. Review PR comes back with its original id and a fresh updated_at. Ship release comes back with a newly generated id. The values shown are the final values of the row, after any SET clause and after BEFORE triggers have run.
Inside DO UPDATE, the proposed row is available as EXCLUDED, and the existing row is available under the table name or its alias:
INSERT INTO tasks AS t (title, status)
VALUES ('Review PR', 'done')
ON CONFLICT (title) DO UPDATE
SET status = EXCLUDED.status,
updated_at = now()
RETURNING t.id, t.title, t.status;The RETURNING list reads the stored row. It describes the row as it exists after the statement, not the values you proposed.
DO UPDATE ... WHERE can silently drop rows
A WHERE clause on the update path lets you skip updates that would change nothing:
INSERT INTO tasks AS t (title, status)
VALUES ('Review PR', 'done')
ON CONFLICT (title) DO UPDATE
SET status = EXCLUDED.status,
updated_at = now()
WHERE t.status IS DISTINCT FROM EXCLUDED.status
RETURNING t.id, t.title, t.status;Run it twice. The first run updates the row and returns it. The second run finds that the status is already done, so the condition is false. The row is left alone, and RETURNING produces zero rows. The row still exists, and the statement still succeeded. It just did not qualify for the update.
This is a good way to avoid pointless writes and trigger activity. It means that zero returned rows does not tell you whether the key exists. It only tells you that nothing was inserted or updated.
Getting the id of an existing row with DO NOTHING
Sometimes you want DO NOTHING because you do not want to modify the existing row, but you still need its id. There are two common approaches.
Approach 1: a no-op update
INSERT INTO tasks (title)
VALUES ('Review PR')
ON CONFLICT (title) DO UPDATE
SET title = EXCLUDED.title
RETURNING id, title;This always returns a row. The cost is that PostgreSQL writes a new version of the existing row, so it fires update triggers, adds dead tuples that vacuum must clean up, and takes a row lock. On a hot table, this adds up.
Approach 2: a data-modifying CTE with a fallback select
WITH ins AS (
INSERT INTO tasks (title)
VALUES ('Review PR')
ON CONFLICT (title) DO NOTHING
RETURNING id, title
)
SELECT id, title, true AS created
FROM ins
UNION ALL
SELECT t.id, t.title, false AS created
FROM tasks AS t
WHERE t.title = 'Review PR'
AND NOT EXISTS (SELECT 1 FROM ins);If the insert succeeded, ins has a row and the second branch returns nothing. If the insert was skipped, ins is empty and the second branch reads the existing row. This writes nothing on the conflict path.
It has a race condition. The final SELECT uses the snapshot taken when the statement started. If another transaction inserts and commits Review PR after that snapshot but before your insert runs, your insert conflicts and is skipped, yet your SELECT cannot see the other transaction's row. In that case you get zero rows. Under READ COMMITTED this is rare, but it can happen. If you need a guaranteed result, use the no-op update, or retry the statement when it returns nothing.
Telling inserted rows from updated rows
Application code often needs to know whether a row was created or updated. You will see this trick in many answers online:
INSERT INTO tasks (title)
VALUES ('Review PR'), ('Deploy')
ON CONFLICT (title) DO UPDATE
SET updated_at = now()
RETURNING id, title, (xmax = 0) AS inserted;xmax is a system column. For a freshly inserted row it is usually 0. For a row that was updated it holds the id of the updating transaction. The trick works in practice, but PostgreSQL does not document that meaning, and it could change. It also gives wrong answers in some cases involving row locks.
Here is the MERGE version:
MERGE INTO tasks AS t
USING (VALUES ('Review PR', 'done'), ('Deploy', 'open')) AS s(title, status)
ON t.title = s.title
WHEN MATCHED THEN
UPDATE SET status = s.status, updated_at = now()
WHEN NOT MATCHED THEN
INSERT (title, status) VALUES (s.title, s.status)
RETURNING merge_action() AS action, t.id, t.title, t.status;action is INSERT or UPDATE for each row. MERGE is not a drop-in replacement for ON CONFLICT. Under concurrent inserts of the same key, MERGE can raise a unique violation, where ON CONFLICT is designed to resolve the race.
Other edge cases
- The same key twice in one statement. If two input rows in a single
INSERTconflict with each other,DO UPDATEfails with "ON CONFLICT DO UPDATE command cannot affect row a second time".DO NOTHINGjust keeps the first. Remove duplicates from the input first, for example withSELECT DISTINCT ON (title). - Output order. Do not rely on the returned rows being in the same order as your
VALUESlist. Return the key column and match rows by key. - BEFORE INSERT triggers. If a
BEFORE INSERTtrigger returnsNULL, that row is skipped and nothing is returned for it. If a trigger changes a column,RETURNINGshows the changed value. - Locking. On the
DO UPDATEpath, PostgreSQL locks the conflicting row even if aWHEREclause then rejects the update. Concurrent writers to that row wait until your transaction ends. - Column references.
RETURNINGreads the target table's columns, using its name or alias. TheEXCLUDEDpseudo-table is for theSETandWHEREclauses of the update action. Read the stored values through the table.
Choosing a pattern
| You need | Use |
|---|---|
| Only the rows that were newly created | `DO NOTHING ... RETURNING` |
| A row back for every input, and updates are acceptable | `DO UPDATE ... RETURNING` |
| Only rows that actually changed | `DO UPDATE ... WHERE ... RETURNING` |
| The existing id without writing to the row | CTE with fallback `SELECT`, with a retry on empty results |
| A documented insert/update flag (PostgreSQL 17+) | `MERGE ... RETURNING merge_action()` |
Exercise
A table tags(id bigint identity primary key, name text unique) already contains 'sql'. You run INSERT INTO tags (name) VALUES ('sql'), ('postgres') ON CONFLICT (name) DO NOTHING RETURNING id, name;. How many rows come back, and which statement change would make a row come back for both names?
Show answer
One row comes back, for 'postgres', because 'sql' conflicts and is skipped. To get a row for both names, change the action to DO UPDATE SET name = EXCLUDED.name, which returns both rows but writes a new version of the existing 'sql' row. Alternatively, use a data-modifying CTE that falls back to a SELECT for the skipped name.
Exercise
Why can INSERT ... ON CONFLICT (title) DO UPDATE SET status = EXCLUDED.status WHERE tasks.status IS DISTINCT FROM EXCLUDED.status RETURNING id return zero rows even though the title exists in the table?
Show answer
The title conflicts, so PostgreSQL takes the update path, but the WHERE condition is false when the stored status already equals the proposed one. The row is neither updated nor returned. Zero rows means nothing was inserted or changed, not that the key is missing.