Video in progress
What does the `MERGE` command in PostgreSQL 15 do, and how does it differ from `INSERT ... ON CONFLICT`?
MERGE compares a source table with the target: it does UPDATE/DELETE for matches and INSERT for non-matches, with several conditions. But unlike ON CONFLICT, it doesn't protect against unique violations on parallel inserts, because it doesn't rely on a unique index.
📖 Answer
A synchronization example: applying prices that arrive from an external system:
MERGE INTO product p
USING staging_prices s ON p.sku = s.sku
WHEN MATCHED AND s.deleted THEN
DELETE
WHEN MATCHED THEN
UPDATE SET price = s.price, updated_at = now()
WHEN NOT MATCHED AND NOT s.deleted THEN
INSERT (sku, price) VALUES (s.sku, s.price);
You can't DELETE with ON CONFLICT, and its conditions are much more limited. MERGE is standard SQL and familiar to people from Oracle and SQL Server.
But there's an important difference, concurrency:
INSERT ... ON CONFLICTworks through a unique index: if a parallel transaction inserts the same key, it waits and then takes the UPDATE path. No error.MERGEdoes the JOIN first. If two transactions both decide "no match" at the same time, both do an INSERT and one fails withduplicate key.
So I follow this rule: a single-row upsert that may arrive in parallel (an API request, a consumer) uses ON CONFLICT. A batch synchronization run by a single process uses MERGE.
PG17 added RETURNING and WHEN NOT MATCHED BY SOURCE to MERGE: deleting rows that are missing from the source is now a single command.
Sign up to mark studied questions and save your progress.