← Back to SQL, page 10

sql-0195 · Hard senior

What does MERGE do in PostgreSQL 15+, and how does it compare with INSERT ... ON CONFLICT?

MERGE compares a source with a target on a join condition and runs different actions for matched and unmatched rows: UPDATE, DELETE, INSERT or DO NOTHING. It can delete as part of the sync, which ON CONFLICT cannot. ON CONFLICT relies on a unique index and handles concurrent inserts more safely. SQLite does not support MERGE.

Full answer
sql
CREATE TABLE stock (sku text PRIMARY KEY, qty int);
CREATE TABLE incoming (sku text, qty int);
INSERT INTO stock VALUES ('pen', 10), ('lamp', 2);
INSERT INTO incoming VALUES ('pen', 15), ('lamp', 0), ('bag', 4);
MERGE INTO stock s USING incoming i ON s.sku = i.sku
WHEN MATCHED AND i.qty = 0 THEN DELETE
WHEN MATCHED THEN UPDATE SET qty = i.qty
WHEN NOT MATCHED THEN INSERT (sku, qty) VALUES (i.sku, i.qty);
SELECT * FROM stock ORDER BY sku;
skuqty
bag4
pen15

'pen' matched and was updated, 'lamp' matched with qty 0 and was deleted, and 'bag' did not match and was inserted. One statement applied the whole change set from incoming.

SQLite rejects the syntax:

sql
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER);
CREATE TABLE incoming (sku TEXT, qty INTEGER);
MERGE INTO stock s USING incoming i ON s.sku = i.sku
WHEN MATCHED THEN UPDATE SET qty = i.qty;
-- error on purpose
text
Error: near "MERGE": syntax error

Choosing between them:

  • ON CONFLICT for single-row or batch upserts keyed by a unique constraint, especially under concurrent writers.
  • MERGE for syncing a staging table into a target, with deletes or several conditional branches.

PostgreSQL's documentation notes that MERGE can still raise unique violations when concurrent sessions insert the same key, which ON CONFLICT is designed to handle.

sql
-- error on purpose
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER);
CREATE TABLE incoming (sku TEXT, qty INTEGER);
MERGE INTO stock s USING incoming i ON s.sku = i.sku
WHEN MATCHED THEN UPDATE SET qty = i.qty;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • MERGE runs actions for matched and unmatched rows
  • It can UPDATE, DELETE or INSERT in one statement
  • PostgreSQL 15+ supports it; SQLite does not
  • ON CONFLICT handles concurrent inserts more safely

Common mistakes

  • Assuming MERGE is concurrency-safe like ON CONFLICT
  • Matching on a non-unique column and updating a row twice

Follow-ups

  • How would you sync a nightly price file into a products table?
  • What does WHEN NOT MATCHED BY SOURCE do in PostgreSQL 17?

Tips

  • Describe the sync use case