Sub topic 2
Anatomy of a `MERGE` Statement
This chapter assumes you know basic SELECT, INSERT, UPDATE, and DELETE statements, joins, primary keys, aliases, and transactions. The examples use PostgreSQL 15 or later, which introduced MERGE.
A MERGE statement compares rows from a source with rows in a target table. A join condition decides whether each source row matches a target row. The statement then chooses an action such as updating a match or inserting a row with no match.
The three main parts
Every MERGE statement has three essential parts:
- The target table after
MERGE INTO. - The source rows after
USING. - The matching rule after
ON.
The target is the table that can be changed. The source is a table, subquery, or other query result that supplies incoming rows. The ON condition works like a join condition. It usually compares a source key with a target key.
Here is a small example setup:
CREATE TABLE inventory (
product_id int PRIMARY KEY,
name text NOT NULL,
quantity int NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE inventory_updates (
product_id int,
name text,
delta int
);
INSERT INTO inventory (product_id, name, quantity) VALUES
(1, 'bolt', 100),
(2, 'nut', 50);
INSERT INTO inventory_updates (product_id, name, delta) VALUES
(2, 'nut', 25),
(3, 'washer', 40);The target contains bolt and nut. The source contains an update for nut and a new product called washer.
Target, source, and aliases
This MERGE uses aliases to make the two row sets clear:
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);MERGE INTO inventory AS t names inventory as the target and gives it the alias t.
USING inventory_updates AS s names inventory_updates as the source and gives it the alias s.
The ON expression compares t.product_id with s.product_id. For source row 2, a target row exists, so the row is matched. For source row 3, no target row exists, so the row is not matched.
The target alias is useful on the right side of an expression, such as t.quantity + s.delta. In an UPDATE SET clause, write the target column on the left without its alias:
UPDATE SET quantity = t.quantity + s.delta`WHEN` clauses
A WHEN clause describes what to do with a row after the ON condition is evaluated.
| Clause | Applies when | Common actions |
|---|---|---|
| `WHEN MATCHED` | A target row matches the source row | `UPDATE`, `DELETE`, or `DO NOTHING` |
| `WHEN NOT MATCHED` | A source row has no target match | `INSERT` or `DO NOTHING` |
WHEN MATCHED can update existing data:
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.deltaIt can also delete a matched target row:
WHEN MATCHED THEN
DELETEWHEN NOT MATCHED commonly inserts the source row:
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta)A MERGE can include several WHEN clauses. PostgreSQL checks them in order. For a particular row, the first qualifying clause is used, so clause order matters when conditions overlap.
Choosing the source query
The source does not have to be a table. A subquery lets you prepare data before matching:
MERGE INTO inventory AS t
USING (
SELECT product_id, max(name) AS name, sum(delta) AS delta
FROM inventory_updates
GROUP BY product_id
) 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);The subquery produces one source row per product_id. That shape is important because one target row must not be matched by multiple source rows in the same MERGE. Deduplicating or aggregating the source belongs in the source query, before the ON condition is applied.
Exercise
In the example, which part decides whether product 2 is updated or product 3 is inserted?
Show answer
The ON condition, t.product_id = s.product_id, decides whether each source row matches a target row. The matching result selects WHEN MATCHED or WHEN NOT MATCHED.