Sub topic 2
Inserting Unmatched Source Rows
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), join conditions, primary keys, and transactions. You need PostgreSQL 15 or later, the first version that supports MERGE.
Inserting unmatched source rows
A WHEN NOT MATCHED branch runs for each source row that has no matching target row under the ON condition. It inserts a new target row built from that source row.
MERGE INTO customers AS t
USING staging_customers AS s
ON t.customer_id = s.customer_id
WHEN NOT MATCHED THEN
INSERT (customer_id, email, updated_at)
VALUES (s.customer_id, s.email, now());Source rows that already exist in the target are not affected by this branch.
Deleting matched rows
A WHEN MATCHED THEN DELETE branch removes the target row whenever a source row matches it. The DELETE branch works the same way as the UPDATE branch, but it removes the row instead of changing it.
Adding conditions and ordering WHEN clauses
Add AND condition after WHEN MATCHED to run a branch only for some matches. PostgreSQL checks the WHEN clauses from top to bottom, and the first branch whose condition is true handles the row. Later branches never see that row.
MERGE INTO inventory AS t
USING shipments AS s
ON t.sku = s.sku
WHEN MATCHED AND s.quantity = 0 THEN
DELETE
WHEN MATCHED THEN
UPDATE SET qty = t.qty + s.quantity
WHEN NOT MATCHED THEN
INSERT (sku, qty) VALUES (s.sku, s.quantity);Exercise
In the inventory example, a shipment with quantity 0 matches an existing SKU. Which branch runs, and what happens to the inventory row?
Show answer
The conditional WHEN MATCHED AND s.quantity = 0 branch runs first, so the matching inventory row is deleted. The general UPDATE branch does not run for that row.