Sub topic 11
MERGE ... RETURNING and merge_action() (PostgreSQL 17+)
This chapter assumes you know basic INSERT, UPDATE, and DELETE, understand primary keys and constraints, and can run statements in PostgreSQL. It focuses on PostgreSQL 17 and later, where MERGE supports a RETURNING clause.
What MERGE does
MERGE compares rows from a source query with rows in a target table. Its ON condition decides whether each source row is matched. A WHEN MATCHED clause usually updates or deletes an existing row. A WHEN NOT MATCHED clause usually inserts a new row.
RETURNING reports the rows affected by those actions. The merge_action() function reports which action happened for each returned row:
| Action | Meaning of `merge_action()` |
|---|---|
| Insert | A new target row was created |
| Update | An existing target row was changed |
| Delete | An existing target row was removed |
A source row that matches no WHEN clause performs no action and produces no returned row.
A complete MERGE example
Suppose the target table stores products and their stock counts:
CREATE TABLE products (
product_code text PRIMARY KEY,
name text NOT NULL,
stock integer NOT NULL
);
INSERT INTO products (product_code, name, stock)
VALUES
('A100', 'Keyboard', 10),
('B200', 'Mouse', 25);The incoming data contains one existing product and one new product:
MERGE INTO products AS p
USING (
VALUES
('A100', 'Keyboard', 12),
('C300', 'Webcam', 8)
) AS incoming(product_code, name, stock)
ON p.product_code = incoming.product_code
WHEN MATCHED THEN
UPDATE SET
name = incoming.name,
stock = incoming.stock
WHEN NOT MATCHED THEN
INSERT (product_code, name, stock)
VALUES (incoming.product_code, incoming.name, incoming.stock)
RETURNING
merge_action() AS action,
p.product_code,
p.name,
p.stock;The result contains one row for each action:
action | product_code | name | stock
--------+--------------+----------+-------
UPDATE | A100 | Keyboard | 12
INSERT | C300 | Webcam | 8The existing A100 row uses the update branch. The new C300 row uses the insert branch. merge_action() lets application code process both results with one result shape.
Conditions and no-op rows
You can add conditions to a WHEN clause. For example, this statement updates stock only when the incoming value differs:
MERGE INTO products AS p
USING (
VALUES ('A100', 'Keyboard', 12)
) AS incoming(product_code, name, stock)
ON p.product_code = incoming.product_code
WHEN MATCHED AND p.stock IS DISTINCT FROM incoming.stock THEN
UPDATE SET stock = incoming.stock
WHEN NOT MATCHED THEN
INSERT (product_code, name, stock)
VALUES (incoming.product_code, incoming.name, incoming.stock)
RETURNING merge_action(), p.product_code, p.stock;If A100 already has stock 12, the WHEN MATCHED condition is false. PostgreSQL performs no action, so that source row does not appear in the RETURNING result.
A MERGE statement evaluates the WHEN clauses in order. After one clause performs an action for a candidate row, later clauses are not used for that row. Design the conditions so that each source row has the intended action.
Reading the result in a client
Treat RETURNING as a result set, not as a row count. A client should read every returned row and inspect action. The result can contain updates and inserts together, and the order is not a reliable business ordering unless you impose ordering elsewhere in the surrounding workflow.
Common mistakes
- Do not assume every source row returns a row. A source row with no matching action returns nothing.
- Do not identify the action from whether a key is null. Use
merge_action(). - Do not rely on the order of returned rows.
- Ensure the source data cannot match the same target row multiple times. A target row being affected more than once by one
MERGEcan cause an error. - Remember that
RETURNINGreports the result of the action. For an update, it shows the updated target values; for an insert, it shows the inserted values.
Exercise
A source row does not match an existing product, but the WHEN NOT MATCHED condition is false. Does RETURNING merge_action() produce a row for that source row?
Show answer
No. No MERGE action occurs, so that source row produces no RETURNING row.