Scrivio Interview library
ConceptIntermediate6 min read · updated 12 November 2026

Explain the SQL MERGE statement as supported in PostgreSQL 15 and later. How does it differ from INSERT ... ON CONFLICT, and when would you prefer each?

MERGE INTO target USING source ON condition compares every source row with the target and applies WHEN MATCHED THEN UPDATE or DELETE and WHEN NOT MATCHED THEN INSERT clauses, so several kinds of change happen in one statement; PostgreSQL 15 introduced it and PostgreSQL 17 added RETURNING and WHEN NOT MATCHED BY SOURCE. Unlike INSERT ... ON CONFLICT, MERGE does not use the unique index to settle races, so two sessions inserting the same new key can still get a unique violation. So I prefer ON CONFLICT for concurrent single-row upserts and MERGE for batch synchronisation from a staging table, including deletes; MySQL 8.4 has no MERGE and uses INSERT ... ON DUPLICATE KEY UPDATE or separate statements.

Why this question is asked

For years PostgreSQL users had one way to say insert or update: INSERT ... ON CONFLICT. Since PostgreSQL 15 there is also MERGE, the SQL standard statement that Oracle and SQL Server users know well. Having two tools for what looks like one job raises an obvious interview question: what is the difference, and when should we use which? The answer depends on concurrency, which is easy to miss. In this answer, we will recap the MERGE syntax, see what PostgreSQL 17 added, compare how MERGE and ON CONFLICT behave under concurrent inserts, and finish with when to prefer each and what to do in MySQL.

1A Quick Recap of the MERGE Syntax

MERGE joins a source, which can be a table, a subquery or a VALUES list, to a target table using an ON condition. Each source row then falls into one of two situations: it matched a target row, or it did not. For each situation we write one or more WHEN clauses with an action, optionally with an extra AND condition. The first clause whose condition holds is applied.

Java
MERGE INTO products t
USING price_feed s
ON t.sku = s.sku
WHEN MATCHED AND s.discontinued THEN
DELETE -- matched, and the feed says it is gone
WHEN MATCHED AND t.price IS DISTINCT FROM s.price THEN
UPDATE SET price = s.price, updated_at = now() -- matched and changed
WHEN NOT MATCHED AND NOT s.discontinued THEN
INSERT (sku, name, price) VALUES (s.sku, s.name, s.price); -- new product
-- MERGE 1270 (rows inserted, updated or deleted in total)
Step throughHow MERGE handles one source row
  1. Join source row to target with ONt.sku = s.sku
  2. Matched a target row?
    YesTry WHEN MATCHED clauses in orderNoTry WHEN NOT MATCHED clauses in order
  3. First clause whose AND condition holdsUPDATE, DELETE, INSERT or DO NOTHING
  4. No clause appliesrow is left unchanged

4 steps in order. Play them, or step through them one at a time.

Notice that one statement does three different things, and that matched rows with an unchanged price fall through every clause and are left alone. This is the strength of MERGE: the whole synchronisation logic is in one place, and the database makes a single pass over the join.

2What PostgreSQL 17 Added

PostgreSQL 17 added two features that close important gaps. RETURNING lets MERGE return the affected rows, together with the function merge_action(), which says whether each row was inserted, updated or deleted. WHEN NOT MATCHED BY SOURCE handles target rows that have no partner in the source, which makes full synchronisation possible in one statement, for example deleting products that are no longer in the feed.

SQL
-- PostgreSQL 17 and later
MERGE INTO products t
USING price_feed s ON t.sku = s.sku
WHEN MATCHED THEN UPDATE SET price = s.price
WHEN NOT MATCHED THEN INSERT (sku, name, price) VALUES (s.sku, s.name, s.price)
WHEN NOT MATCHED BY SOURCE THEN DELETE -- in the table but not in the feed
RETURNING merge_action(), t.sku;
-- UPDATE | A-100
-- INSERT | B-205
-- DELETE | Z-999

On PostgreSQL 15 and 16, neither exists, so we would need a separate DELETE ... WHERE NOT EXISTS for the missing rows and could not get the changed rows back from MERGE. Since these details depend on the version, check the version of each environment before relying on them.

3How ON CONFLICT Differs

INSERT ... ON CONFLICT starts from the other end. It tries to insert each row, and if the insert would violate a specific unique index or constraint, the conflict target, it performs the DO UPDATE or DO NOTHING action instead. It only handles that one situation, insert or else update, and it cannot delete rows or act on rows that are missing from the input.

SQL
INSERT INTO products (sku, name, price)
VALUES ('A-100', 'Kettle', 39.90)
ON CONFLICT (sku) DO UPDATE
SET price = EXCLUDED.price -- EXCLUDED is the row we tried to insert
RETURNING id;

The important difference is how it gets its answer. ON CONFLICT relies on the unique index itself to decide whether the row exists, using a mechanism called speculative insertion: it inserts, and if another session inserted the same key at the same moment, it waits for that session and then updates the row instead. So it always ends in either an insert or an update, even under heavy concurrency.

4Why MERGE Is Not Race-Free

MERGE decides matched or not matched from the join, using the snapshot of the statement. If two sessions run MERGE at the same moment for the same new key, both see no matching row, both choose the NOT MATCHED branch, and both insert. The unique index then rejects the second insert with a unique violation. The PostgreSQL documentation states that MERGE does not give the insert-or-update guarantee that ON CONFLICT does.

Step throughTwo sessions merging the same new SKU
Session APostgreSQLSession B
MERGE ... sku 'N-1'
MERGE ... sku 'N-1'
both see no match: NOT MATCHED
INSERT N-1 succeeds
ERROR: duplicate key violates unique constraint

5 messages in order. Play them, or step through them one at a time.

With INSERT ... ON CONFLICT, session B would wait for A and then update instead.

For a nightly batch, run by one job at a time, this race never happens. For an API where many requests may upsert the same key at once, it does, and the application would have to catch the error and retry. That is why the choice is mostly about concurrency.

5When to Prefer Each

I prefer INSERT ... ON CONFLICT for high-concurrency, row-at-a-time upserts: counters, idempotent event handling, caches of external data written by many requests. It is designed for exactly that and never fails with a duplicate key on its conflict target. I prefer MERGE for batch synchronisation from a staging table: one job compares a full feed with the table and inserts, updates and deletes in one pass, with clear per-case conditions, and since PostgreSQL 17 it can also delete rows missing from the source and return what it did.

MySQL 8.4 has no MERGE statement. Its upsert is INSERT ... ON DUPLICATE KEY UPDATE, which behaves like ON CONFLICT DO UPDATE against any unique key that conflicts. For deletes in a batch synchronisation, we write a separate DELETE with a join or NOT EXISTS, in the same transaction.

ON CONFLICT or MERGE
NeedINSERT ... ON CONFLICTMERGE (PostgreSQL 15+)
Concurrent single-row upsertYes: race-free via unique indexCan raise unique violation
Update and delete in one statementNoYes
Act on rows missing from the sourceNoPostgreSQL 17+: NOT MATCHED BY SOURCE
Return affected rowsRETURNINGPostgreSQL 17+: RETURNING, merge_action()
MySQL 8.4ON DUPLICATE KEY UPDATENot available

6Follow-up questions

Can MERGE be used from Spring Data JPA?

Not through repository methods, since JPA has no MERGE concept; EntityManager.merge() is something else entirely, it copies a detached entity's state into the persistence context. We run SQL MERGE as a native query, through JdbcTemplate, or with jOOQ, which supports MERGE in its DSL. Because it is a bulk statement, we should also clear or refresh any entities already loaded in the persistence context afterwards.

Does MERGE lock rows?

Yes. Updated and deleted target rows are locked like in UPDATE and DELETE. At READ COMMITTED, if a matched row was concurrently updated, PostgreSQL re-checks the conditions against the new version of the row before acting, much as UPDATE does. Inserted rows are protected by the unique index, which is where the race we described shows up.

7Conclusion

In this answer, we saw that MERGE joins a source to a target and applies WHEN MATCHED and WHEN NOT MATCHED actions, including deletes, in one statement, and that PostgreSQL 17 added RETURNING and WHEN NOT MATCHED BY SOURCE. ON CONFLICT uses the unique index to make each upsert race-free, while MERGE can raise a unique violation under concurrent inserts of the same key, so ON CONFLICT suits concurrent single-row upserts and MERGE suits batch synchronisation, with MySQL 8.4 offering only ON DUPLICATE KEY UPDATE.

What to say in the interviewAbout 80 seconds aloud

Open with

MERGE INTO target USING source ON a join condition, then WHEN MATCHED THEN UPDATE or DELETE and WHEN NOT MATCHED THEN INSERT, each with an optional extra condition.

Then, if they want more

It lets one statement insert, update and delete, which makes it great for syncing a table from a staging table or feed. PostgreSQL added it in version 15, and version 17 added RETURNING with merge_action, plus WHEN NOT MATCHED BY SOURCE, so you can delete target rows that disappeared from the feed; I'd check the version before using those.

INSERT ON CONFLICT is narrower: it tries to insert and, if a specific unique index reports a conflict, it updates or does nothing. The key difference is concurrency. ON CONFLICT uses the unique index to decide, so two sessions upserting the same new key end with one insert and one update.

MERGE decides from its snapshot, so both sessions may take the NOT MATCHED branch and one fails with a unique violation. So for high-concurrency single-row upserts, like counters or idempotent event handling, I use ON CONFLICT. For batch synchronization run by one job, including deletes, I use MERGE.

MySQL 8.4 has no MERGE, so there I'd use INSERT ON DUPLICATE KEY UPDATE and a separate DELETE.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 17, MySQL 8.4, PostgreSQL 15
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain the SQL MERGE statement as supported in PostgreSQL 15 and later. How does it...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/59d7856f2c/