Sub topic 3
Handling duplicate source rows
This chapter assumes you can write MERGE with a join condition and WHEN branches, know how primary keys work, and understand transactions at the READ COMMITTED level. MERGE exists in PostgreSQL 15 and later. The WHEN NOT MATCHED BY SOURCE clause and RETURNING merge_action() require PostgreSQL 17.
Handling duplicate source rows
MERGE fails when one target row matches two or more source rows. PostgreSQL raises MERGE command cannot affect row a second time. Deduplicate the source before the merge runs:
MERGE INTO customers AS t
USING (
SELECT DISTINCT ON (customer_id) customer_id, email
FROM staging_customers
ORDER BY customer_id, updated_at DESC
) AS s
ON t.customer_id = s.customer_id
WHEN MATCHED THEN
UPDATE SET email = s.email
WHEN NOT MATCHED THEN
INSERT (customer_id, email) VALUES (s.customer_id, s.email);Handling target rows missing from the source
WHEN NOT MATCHED BY SOURCE handles target rows with no source match. Add a condition before deleting, because an unfiltered delete removes every row the source omitted.
Inspecting results with RETURNING
In PostgreSQL 17, RETURNING merge_action() reports whether each row was inserted, updated, or deleted.
Concurrent writes and isolation levels
Under READ COMMITTED, two concurrent MERGE statements can both find no match and both try to insert, and one fails with a unique violation. A higher isolation level can instead fail with a serialization error, so the application must retry.
MERGE or INSERT ... ON CONFLICT
For a simple upsert keyed on a unique column, INSERT ... ON CONFLICT is safer under concurrency. It waits for the conflicting row and then updates it. Use MERGE when you need delete branches, several conditions, or multiple action types in one statement.
Exercise
Your staging table has two rows for customer_id 7. Which clause prevents the "cannot affect row a second time" error?
Show answer
Deduplicate the source with SELECT DISTINCT ON (customerid) ... ORDER BY customerid, updatedat DESC, so that only one row per customerid reaches the MERGE.