Sub topic 10
Returning Results with `merge_action()` in PostgreSQL 17
Assume you understand basic joins, transactions, and the earlier MERGE clauses. This chapter focuses on PostgreSQL 17 features that let a MERGE statement report what it changed.
Why return results from `MERGE`?
Before PostgreSQL 17, MERGE could insert, update, delete, or skip rows, but it did not provide a RETURNING clause. Applications that needed to know which action occurred often had to run another query or maintain separate logging.
PostgreSQL 17 added:
RETURNINGforMERGEmerge_action(), which reports the action taken for each returned rowWHEN NOT MATCHED BY SOURCE, which can act on target rows absent from the source
merge_action() returns one of these text values:
| Value | Meaning |
|---|---|
| `INSERT` | A source row created a new target row |
| `UPDATE` | A matching target row was updated |
| `DELETE` | A target row was deleted |
A row skipped by DO NOTHING is not returned.
A complete example
The following example creates temporary tables, synchronizes them, and returns the action and final target values. Temporary tables exist only for the current database session.
DROP TABLE IF EXISTS inventory_updates;
DROP TABLE IF EXISTS inventory;
CREATE TEMP TABLE inventory (
product_id int PRIMARY KEY,
name text NOT NULL,
quantity int NOT NULL
);
CREATE TEMP TABLE inventory_updates (
product_id int,
name text,
delta int
);
INSERT INTO inventory (product_id, name, quantity) VALUES
(1, 'bolt', 100),
(2, 'nut', 50),
(3, 'washer', 40);
INSERT INTO inventory_updates (product_id, name, delta) VALUES
(2, 'nut', 25),
(4, 'screw', 12);
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.name,
t.quantity;The result contains one row for each affected target row. The update changes the nut quantity from 50 to 75. The screw is inserted. The bolt and washer are deleted because they have no corresponding source row.
The output might look like this:
| action | product_id | name | quantity |
|---|---|---|---|
| UPDATE | 2 | nut | 75 |
| INSERT | 4 | screw | 12 |
| DELETE | 1 | bolt | 100 |
| DELETE | 3 | washer | 40 |
The order of returned rows is not guaranteed unless you process the result in a way that does not depend on ordering. For example, do not assume that all updates appear before inserts.
How `merge_action()` works
merge_action() is evaluated for each row affected by the MERGE. It identifies the action selected by the matching and WHEN clauses, not the reason that the source row was present.
For an update, columns in RETURNING show the updated target values. For a delete, the deleted target row's values can be returned. For an insert, the newly inserted values can be returned.
You can return expressions as well as columns:
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,
t.product_id,
t.quantity,
t.quantity * 2 AS quantity_for_report;The returned data is the result of the current statement. It is not a permanent audit record. If the transaction later rolls back, the changes and their returned results are rolled back from the database's point of view. Store the returned rows separately if you need a durable history.
Understanding `WHEN NOT MATCHED BY SOURCE`
WHEN NOT MATCHED BY SOURCE examines target rows for which no source row matched the ON condition. It is useful when the source represents the complete desired state.
For example, this clause removes products that are no longer present in the source:
WHEN NOT MATCHED BY SOURCE THEN
DELETEYou can add a condition to protect certain rows:
WHEN NOT MATCHED BY SOURCE
AND t.product_id <> 1 THEN
DELETEBe careful with this clause when the source is only a partial change set. A partial source means “change these rows,” while NOT MATCHED BY SOURCE treats missing source rows as candidates for action. Using the clause with a partial source can delete or update valid target rows.
Choosing the returned columns
A practical application often returns an action, a stable identifier, and values needed by the next step:
Return only the columns the caller needs. Returning large payloads increases network and application work.
Exercise
Exercise
What will merge_action() return for a target row that matches a source row but satisfies a WHEN MATCHED AND condition clause that leads to DO NOTHING?
Show answer
No row is returned for that target row, because DO NOTHING affects no row.