Sub topic 10
Returning results with merge_action() (PostgreSQL 17)
This chapter assumes you can write a basic MERGE with WHEN MATCHED and WHEN NOT MATCHED clauses and that you understand INSERT ... RETURNING. It also uses the inventory and inventory_updates tables from the first chapter. Everything here needs PostgreSQL 17 or later. On version 16 or earlier, MERGE accepts no RETURNING clause and the statement fails with a syntax error.
The problem: MERGE hides what it did
A MERGE can insert, update, and delete in a single statement. Before PostgreSQL 17, the only feedback was the command tag, such as MERGE 2. That tag is the total number of rows affected. It does not say how many were inserted, how many were updated, or which products were involved.
Callers often need exactly that information:
- An audit table that records each change.
- An API that reports to the user which records were created and which were changed.
- A job that logs how many rows each action touched.
Before version 17 you had to run extra queries, compare snapshots, or split the work into separate statements. PostgreSQL 17 adds a RETURNING clause to MERGE, plus a function, merge_action(), that reports which clause fired for each row.
RETURNING on MERGE
RETURNING goes at the end of the statement, after the last WHEN clause. It works like RETURNING on INSERT, UPDATE, and DELETE: the statement produces one result row for each target row that was inserted, updated, or deleted. The expression list can refer to:
- columns of the target table (
t.product_id, ort.*) - columns of the source (
s.delta) - the function
merge_action()
Here is the first merge from the tutorial with a RETURNING clause added. It is wrapped in a transaction that is rolled back, so you can run it repeatedly without changing your data.
BEGIN;
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)
RETURNING merge_action() AS action,
t.product_id,
t.name,
t.quantity,
s.delta;
ROLLBACK;With the starting data from the first chapter, the result is:
action | product_id | name | quantity | delta
--------+------------+--------+----------+-------
UPDATE | 2 | nut | 75 | 25
INSERT | 3 | washer | 40 | 40Nut already existed, so the WHEN MATCHED clause ran and merge_action() returned UPDATE. Washer did not exist, so the WHEN NOT MATCHED clause ran and it returned INSERT. Bolt does not appear because no source row matched it and this statement has no clause for that case.
The row order is not guaranteed. It follows whatever order the join produced. If you need a stable order, put the MERGE in a CTE and sort in the outer query, as shown later.
What merge_action() returns
merge_action() returns text, always one of three uppercase strings: INSERT, UPDATE, or DELETE. It reports the action actually taken for that row. It does not report the clause type. A WHEN NOT MATCHED BY SOURCE THEN DELETE clause returns DELETE, as does a WHEN MATCHED ... THEN DELETE clause.
Two rules apply:
- You can call it only in the
RETURNINGlist of aMERGE. Anywhere else, PostgreSQL raises an error. - A row handled by
DO NOTHINGproduces no result row, because nothing was inserted, updated, or deleted.
Give the function an alias, as in merge_action() AS action. Without one, the column is named merge_action, which is awkward in later queries.
Which values do the columns show?
The target columns in RETURNING depend on the action that ran. The source columns come from the source row, if there is one.
| Action | Target columns (`t.*`) | Source columns (`s.*`) |
|---|---|---|
| INSERT | The new row as stored | The source row |
| UPDATE | The row after the update | The source row |
| DELETE from `WHEN MATCHED` | The row as it was before deletion | The source row |
| DELETE from `WHEN NOT MATCHED BY SOURCE` | The row as it was before deletion | All NULL |
The last row of the table matters most. When the action comes from NOT MATCHED BY SOURCE, no source row exists, so every s. column is NULL. Code that reads s.product_id for deleted rows gets NULL. Use t.product_id when you need the key in every case.
Replace the empty block above with the diagram below. It shows how a row reaches the result.
A full example with NOT MATCHED BY SOURCE
Combine RETURNING with the WHEN NOT MATCHED BY SOURCE clause from the previous chapter. This statement synchronizes inventory with the update list: matched rows are updated, new rows are inserted, and target rows with no source row are deleted.
BEGIN;
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)
WHEN NOT MATCHED BY SOURCE THEN
DELETE
RETURNING merge_action() AS action, t.product_id, t.quantity;
ROLLBACK;With the starting data, the result has three rows, in some order:
action | product_id | quantity
--------+------------+----------
DELETE | 1 | 100
UPDATE | 2 | 75
INSERT | 3 | 40The DELETE row shows quantity 100, the value the bolt row had when it was removed. That is useful: you can see exactly what disappeared without running a SELECT first.
The UPDATE row shows 75, the new value. In PostgreSQL 17 you cannot see the old quantity (50) in RETURNING. You can derive it from the source (t.quantity - s.delta for an update that added the delta). Newer PostgreSQL releases add OLD and NEW aliases to RETURNING, so check your version's documentation if you need both values.
Using the results: MERGE inside a CTE
Most applications do more than print the rows. PostgreSQL 17 lets you put a MERGE ... RETURNING in a WITH query, so the outer statement can filter, sort, aggregate, or insert the rows.
Counting rows per action
BEGIN;
WITH changes AS (
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)
RETURNING merge_action() AS action
)
SELECT action, count(*) AS row_count
FROM changes
GROUP BY action
ORDER BY action;
ROLLBACK;This returns one INSERT row and one UPDATE row, each with a count of 1. It is the per-action breakdown that the old MERGE 2 command tag could not provide.
Writing an audit trail
The same pattern records every change in an audit table, in one statement and one transaction:
CREATE TABLE inventory_audit (
audit_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
action text NOT NULL,
product_id int NOT NULL,
quantity int NOT NULL,
logged_at timestamptz NOT NULL DEFAULT now()
);
WITH changes AS (
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)
RETURNING merge_action() AS action, t.product_id, t.quantity
)
INSERT INTO inventory_audit (action, product_id, quantity)
SELECT action, product_id, quantity
FROM changes;Because the MERGE and the audit INSERT are one statement, they succeed or fail together. If the merge raises an error, no audit rows are written, and the reverse also holds.
Common errors
- Using RETURNING on an older server. PostgreSQL 15 and 16 have
MERGEbut noRETURNINGfor it. Check withSHOW server_version;. If the server is older than 17, the statement fails at theRETURNINGkeyword. - Calling merge_action() outside RETURNING. The function exists only inside the
RETURNINGlist of aMERGE. Using it in aSELECT, in aWHEREclause, or in theSETlist raises an error. - Reading source columns for deleted rows. For
WHEN NOT MATCHED BY SOURCErows, alls.columns are NULL. Returnt.product_idinstead ofs.product_id. - Duplicate column names in a CTE. If you write
RETURNING t.product_id, s.product_idinside aWITHquery, the outer query sees two columns with the same name and cannot refer to either of them. Alias each expression. - Filtering inside RETURNING.
RETURNINGhas noWHERE. If you want only the inserted rows, put theMERGEin a CTE and filter in the outer query withWHERE action = 'INSERT'. - Expecting a row for DO NOTHING. Rows that match a
DO NOTHINGclause, or no clause at all, are not returned. If you count rows fromRETURNINGand compare the total to the source size, the totals differ by the number of skipped rows.
Choosing what to return
- Application responses: return the keys and the final values (
t.product_id,t.quantity) along withmerge_action(), so the caller can tell created records from changed ones. - Auditing: use the CTE pattern with an
INSERTinto the audit table. This keeps the log consistent with the data. - Monitoring: aggregate per action, as in the count example, and log the totals.
- Large merges:
RETURNINGsends one row for every changed row. For a merge that changes millions of rows, that is a large result. If you only need counts, aggregate inside a CTE so only a few rows leave the server.
Exercise
A MERGE statement on PostgreSQL 17 has WHEN MATCHED THEN UPDATE, WHEN NOT MATCHED THEN INSERT, and WHEN NOT MATCHED BY SOURCE THEN DELETE, followed by RETURNING mergeaction() AS action, s.productid. A caller reports that the product_id column is NULL for some rows. Which rows are they, and how do you fix the query?
Show answer
They are the rows where action is DELETE and the clause was WHEN NOT MATCHED BY SOURCE. Those target rows have no source row, so every s. column is NULL. Return t.productid instead (the target key is present for INSERT, UPDATE, and DELETE), or use coalesce(s.productid, t.product_id).
Exercise
Write a statement that merges inventoryupdates into inventory (update matched rows by adding delta, insert unmatched rows) and returns only the rows that were inserted, as productid and quantity.
Show answer
Put the MERGE in a CTE and filter in the outer query: WITH changes AS ( MERGE INTO inventory AS t USING inventoryupdates AS s ON t.productid = s.productid WHEN MATCHED THEN UPDATE SET quantity = t.quantity + s.delta WHEN NOT MATCHED THEN INSERT (productid, name, quantity) VALUES (s.productid, s.name, s.delta) RETURNING mergeaction() AS action, t.productid, t.quantity ) SELECT productid, quantity FROM changes WHERE action = 'INSERT'; RETURNING itself cannot filter rows, so the filter belongs in the outer query. All rows are still merged. Only the displayed rows are limited.
Exercise
A merge has a WHEN MATCHED AND s.delta = 0 THEN DO NOTHING clause ahead of the update clause. The source has 10 rows, and 3 of them have delta = 0 and match existing rows. How many rows does RETURNING produce, assuming the remaining rows are all matched or inserted?
Show answer
7. The three DO NOTHING rows change nothing, so they produce no RETURNING rows. Only inserted, updated, or deleted rows are returned.