Sub topic 11
MERGE ... RETURNING and merge_action() (PostgreSQL 17+)
This chapter assumes you have read the earlier chapters on INSERT, UPDATE, DELETE and ON CONFLICT with RETURNING. It also assumes you know the basic shape of MERGE. You need PostgreSQL 17 or later to run the examples. On PostgreSQL 16 and earlier, MERGE does not accept a RETURNING clause and fails with a syntax error.
Why MERGE needs its own RETURNING
MERGE compares a source (a table, subquery or VALUES list) with a target table. For each source row it decides whether to insert, update or delete a target row, or to do nothing. One statement can therefore change rows in three different ways.
Before PostgreSQL 17, MERGE returned only a row count in its command tag, such as MERGE 2. You could not tell which rows were inserted and which were updated. With RETURNING, each changed row comes back. The function merge_action() tells you which action produced it.
Setup
The examples use a small table and recreate it before each run so the output is predictable. The columns match the tasks table from earlier chapters.
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 basic form
The RETURNING clause goes at the end of the MERGE statement. It can include the target's columns, the source's columns, and merge_action().
MERGE INTO tasks AS t
USING (VALUES ('Review PR', 'done'), ('Plan sprint', '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;On the freshly created table, the result is:
action | id | title | status
--------+----+-------------+--------
UPDATE | 2 | Review PR | done
INSERT | 3 | Plan sprint | openNotes on this output:
Review PRalready existed, so the first clause ran andmerge_action()returnedUPDATE.Plan sprintdid not exist, so the second clause ran and the function returnedINSERT. The identity value3was generated during the merge and comes back without a second query.- The row order is not guaranteed, as with any
RETURNING. - If you do not give
merge_action()an alias, the output column is namedmerge_action.
What merge_action() returns
merge_action() returns one of three text values: 'INSERT', 'UPDATE' or 'DELETE'. The values are always uppercase.
- You can use it only in the
RETURNINGlist of aMERGE. In other statements and in other parts ofMERGE, such as theONcondition or aWHEN ... ANDcondition, it raises an error. - It is an ordinary expression inside
RETURNING. You can compare it, wrap it inCASE, or pass it to other functions. - It never returns a value for
DO NOTHING, because that action produces no row (see below).
RETURNING
t.id,
merge_action() = 'INSERT' AS was_createdWhich values each action returns
The values you see for the target columns depend on the action. This matches what you learned for the separate statements.
| Action | Target columns in RETURNING | Source columns in RETURNING |
|---|---|---|
| `INSERT` | The new row, including defaults and generated keys | The source row that caused the insert |
| `UPDATE` | The row after the update | The matching source row |
| `DELETE` | The row as it was just before deletion | The matching source row |
| `DO NOTHING` | No row is returned | No row is returned |
The DELETE case is worth a demonstration. The source row says cancelled, but the target row is returned with its old values.
MERGE INTO tasks AS t
USING (VALUES ('Write report', 'cancelled')) AS s(title, status)
ON t.title = s.title
WHEN MATCHED AND s.status = 'cancelled' THEN
DELETE
WHEN MATCHED THEN
UPDATE SET status = s.status
RETURNING merge_action() AS action, t.id, t.title, t.status AS target_status, s.status AS source_status; action | id | title | target_status | source_status
--------+----+--------------+---------------+---------------
DELETE | 1 | Write report | open | cancelledHere t.status is open, the value the row had when it was deleted. Using both aliases lets the caller log what was removed and why.
Rows that produce no output
A source row produces output only when one of its actions is INSERT, UPDATE or DELETE. Three cases return nothing:
- The row matches a
WHENclause withDO NOTHING. - The row matches no
WHENclause. For example, it is matched but only aWHEN NOT MATCHEDclause exists. - The row matches a
WHEN ... AND conditionclause whose condition is false, and no later clause applies.
This is the same behavior as ON CONFLICT DO NOTHING, which also returns no row for a skipped input. If you need to report skipped rows, RETURNING cannot help. Compare your input count with the returned count, or select the skipped keys separately.
Target rows with no source row
PostgreSQL 17 also added WHEN NOT MATCHED BY SOURCE. It acts on target rows that have no matching source row. It is useful for synchronizing a table with a full snapshot of data.
Because no source row exists in this case, every source column in RETURNING is NULL. Always read the key from the target for these rows.
MERGE INTO tasks AS t
USING (VALUES ('Review PR')) AS s(title)
ON t.title = s.title
WHEN NOT MATCHED BY SOURCE THEN
DELETE
RETURNING merge_action() AS action, t.id, t.title, s.title AS source_title;If the table holds three tasks and only Review PR is in the source, the other two come back with DELETE and a NULL source_title. The reverse holds for WHEN NOT MATCHED (by target): the target columns reflect the newly inserted row, so they are not NULL.
Using MERGE ... RETURNING in a CTE
PostgreSQL 17 also allows MERGE with RETURNING inside a WITH query. This works like the data-modifying CTEs you saw earlier. You can summarize what a merge did in a single statement:
WITH merged AS (
MERGE INTO tasks AS t
USING (VALUES ('Review PR', 'done'), ('Plan sprint', 'open')) AS s(title, status)
ON t.title = s.title
WHEN MATCHED THEN
UPDATE SET status = s.status
WHEN NOT MATCHED THEN
INSERT (title, status) VALUES (s.title, s.status)
RETURNING merge_action() AS action, t.id
)
SELECT action, count(*) AS rows_changed
FROM merged
GROUP BY action
ORDER BY action;The outer query sees only the rows that RETURNING produced, and the whole statement is atomic. You can also feed the rows into another INSERT, for example to write an audit table with the action name in one column.
MERGE or INSERT ... ON CONFLICT?
Both can create a row or update an existing one and return the result. Choose by the guarantees you need.
| Question | `INSERT ... ON CONFLICT` | `MERGE` |
|---|---|---|
| Requires a unique index to detect duplicates | Yes, named in the conflict target | No, any `ON` condition works |
| Safe against concurrent inserts of the same key | Yes, it is built for this | No, a concurrent insert can cause a unique violation or a duplicate |
| Can delete rows | No | Yes |
| Can tell insert from update in `RETURNING` | Not directly. People often check `xmax = 0`, which is an implementation detail | Yes, with `merge_action()` |
| Can have several conditional branches | One `DO UPDATE ... WHERE` | Many `WHEN` clauses with conditions |
For a simple "insert this key or update it" operation under concurrent load, ON CONFLICT is still the safer tool. Use MERGE when you need several actions, deletions, or a clean label for each row.
Edge cases
- Version limits.
RETURNINGinMERGEandmerge_action()need PostgreSQL 17. Code that must run on 16 or earlier has to useINSERT ... ON CONFLICTor separate statements. - Source columns exist only when a source row exists. They are
NULLinWHEN NOT MATCHED BY SOURCErows. - Updatable views. Since PostgreSQL 17,
MERGEworks on updatable views, andRETURNINGworks with them. Rules are not supported onMERGEtargets. - Triggers. Row-level triggers fire for each action as they do for the matching plain statement. A
BEFOREtrigger that changes the row is reflected inRETURNING. - Old and new values. On PostgreSQL 18 and later,
RETURNING old.col, new.colalso works inMERGE. For anINSERTaction, theoldvalues areNULL. For aDELETEaction, thenewvalues areNULL. - Client code. Reading the results works the same as for other statements. The statement returns a result set, so use your driver's query method, not the "execute without result" method.
Exercise
A table stock(sku text PRIMARY KEY, qty int NOT NULL) holds current stock. You receive a list of (sku, delta) pairs. For each pair, if the SKU exists, add delta to qty. If the resulting quantity would be zero or less, delete the row. If the SKU does not exist and delta is positive, insert it. Write one MERGE statement that returns the action, the SKU and the quantity the row had at the end, or the quantity it had just before deletion.
Show answer
MERGE INTO stock AS t
USING (VALUES ('A1', -5), ('B2', 10)) AS s(sku, delta)
ON t.sku = s.sku
WHEN MATCHED AND t.qty + s.delta <= 0 THEN
DELETE
WHEN MATCHED THEN
UPDATE SET qty = t.qty + s.delta
WHEN NOT MATCHED AND s.delta > 0 THEN
INSERT (sku, qty) VALUES (s.sku, s.delta)
RETURNING merge_action() AS action, t.sku, t.qty;
The DELETE clause comes first because the first matching clause wins. In the DELETE row, t.qty is the quantity just before deletion. Source rows that are new with a non-positive delta match no clause, so they return nothing.
Exercise
Why does a MERGE row handled by DO NOTHING not appear in the RETURNING output, and how can you find out how many source rows were skipped?
Show answer
DO NOTHING changes no target row, and RETURNING reports only rows that were inserted, updated or deleted. To count skipped rows, subtract the number of returned rows from the number of source rows, for example by wrapping the MERGE in a CTE and comparing count(*) of its output with count(*) of the source.