Two statements that look interchangeable
PostgreSQL 15 added MERGE, the SQL standard statement that joins a source to a target and runs different actions for matched and unmatched rows. A common first use is the stock counter: when a delivery of books arrives, add the quantity to the existing row for that ISBN, or insert a new row if the ISBN is new.
MERGE INTO book_stock AS s
USING (VALUES ($1, $2)) AS v(isbn, qty)
ON s.isbn = v.isbn
WHEN MATCHED THEN UPDATE SET qty = s.qty + v.qty
WHEN NOT MATCHED THEN INSERT (isbn, qty) VALUES (v.isbn, v.qty);The older way to write the same thing is INSERT ... ON CONFLICT DO UPDATE:
INSERT INTO book_stock (isbn, qty) VALUES ($1, $2)
ON CONFLICT (isbn) DO UPDATE SET qty = book_stock.qty + EXCLUDED.qty;With one session they behave the same. With two sessions delivering the same new ISBN at the same moment, they do not, and the PostgreSQL documentation says so directly. In the chapter on transaction isolation, a MERGE with both insert and update actions "looks similar to INSERT with an ON CONFLICT DO UPDATE clause but does not guarantee that either INSERT or UPDATE will occur." The MERGE reference page suggests INSERT ... ON CONFLICT as an alternative "which offers the ability to run an UPDATE if a concurrent INSERT occurs."
Measured on PostgreSQL 18.4
I ran both statements against a disposable local PostgreSQL 18.4 cluster with psycopg 3. Session A runs its statement for a new ISBN with quantity 3 and does not commit. Session B runs the same statement for the same ISBN with quantity 2, which blocks on A's uncommitted row in the primary key index. After one second A commits, and B continues.
| Statement | Isolation | Session B result | Final quantity |
|---|---|---|---|
MERGE | Read Committed | 23505 unique_violation | 3 |
INSERT ... ON CONFLICT DO UPDATE | Read Committed | committed | 5 |
MERGE | Repeatable Read | 23505 unique_violation | 3 |
INSERT ... ON CONFLICT DO UPDATE | Repeatable Read | 40001 serialization_failure | 3 |
At Read Committed, the default, MERGE in session B decided "not matched" from its snapshot, attempted the insert, waited for A, and then failed with a duplicate key error when A committed. INSERT ... ON CONFLICT waited for A too, but then took the conflict path and added 2 to A's 3. At Repeatable Read neither statement can see A's row, so neither can update it: ON CONFLICT reports a serialization failure, which tells the caller to retry the transaction, while MERGE still reports a unique violation.
The difference is in the guarantee. ON CONFLICT is designed around the arbiter index: each proposed row either inserts or, if the index reports a conflict, takes the update path, even when the conflicting row was committed by a transaction the statement's snapshot cannot see (at Read Committed). MERGE evaluates its join against the snapshot and then executes the chosen action; when a concurrent insert makes the chosen insert impossible, the index raises the error.
What this means for application code
A MERGE used as an upsert on a key that concurrent writers can create needs one of three things:
- Use
INSERT ... ON CONFLICTinstead when the operation really is "insert or update this one row by a unique key". It is the statement built for that, and at Read Committed it gives the either-or guarantee. - Retry on
23505when you needMERGEfor somethingON CONFLICTcannot express, such as aDELETEaction, conditions on the source, or several target rows from a join. The retry will find the row on the second attempt and take the matched branch. Make sure the whole transaction is safe to repeat. - Serialise writers for the key with a lock, for example a transaction-level advisory lock on a stable 64-bit hash of the ISBN computed in the application, taken with
pg_advisory_xact_lockbefore theMERGE, when retries would be expensive. This costs concurrency and should be measured.
import psycopg
from psycopg import errors
def add_stock(conn: psycopg.Connection, isbn: str, qty: int, attempts: int = 3) -> None:
for attempt in range(attempts):
try:
with conn.transaction():
conn.execute(MERGE_SQL, (isbn, qty))
return
except errors.UniqueViolation:
if attempt == attempts - 1:
raiseThe retry loop is only correct because the transaction contains nothing else that could have committed side effects. If the MERGE runs inside a larger transaction, the retry must restart that whole transaction, which usually means the retry belongs at the unit-of-work boundary, not around the statement.
At Repeatable Read or Serializable, both statements can fail and the application must already retry serialization failures. Add 23505 from MERGE to the retryable set only for the keys where a concurrent first insert is expected; elsewhere a duplicate key is a real bug and should surface.
Where MERGE is still the right choice
MERGE earns its place for batch synchronisation where the source is a set, not a single row: applying a supplier's nightly price file to the catalogue, with updates for changed prices, inserts for new titles and deletes for withdrawn ones, in one statement with one plan. In that pattern the job is usually the only writer of those rows, so the concurrency problem does not arise. If other writers can insert the same keys while the job runs, the same failure applies, and a failed batch is more expensive to retry than a single row, so partition the batch or coordinate the writers.
MERGE also has features ON CONFLICT lacks: WHEN NOT MATCHED BY SOURCE (added in PostgreSQL 17) to act on target rows missing from the source, multiple WHEN clauses with conditions, and RETURNING with merge_action() to report which action ran per row. None of these change the concurrency behaviour.
Finding the risky statements in an existing codebase
Search for MERGE INTO in application code and migrations, and classify each use by two questions. Can another session insert a row with the same key while this statement runs? And is the statement inside a transaction that also does other work? Statements where the first answer is no, such as a nightly job that is the only writer of a staging table, need nothing. Statements where the first answer is yes need one of the three remedies above, and the second answer tells you where a retry must go.
Also look at how errors are handled around those statements. A generic handler that logs and continues on any database error turns the race into silent data loss, as the measured final quantity of 3 instead of 5 shows. A handler that returns an HTTP 500 at least makes the failure visible, and a client that retries the whole request will usually succeed on the second attempt, which is why these failures are often noticed late: the retry hides them until load increases.
Failure modes
- Rare duplicate key errors under load from a code path that only ever inserts new keys through
MERGE. They appear when two requests create the same key together, which tests with one client never do. - Lost increments when catching the error and moving on. Swallowing
23505drops session B's quantity: the measured final quantity was 3, not 5. - Retrying inside a transaction that already wrote other rows, so the retry duplicates those writes. Retry the unit of work.
- Assuming Repeatable Read makes it safe. It changes the error, not the need to retry.
- Upgrading from
ON CONFLICTtoMERGEfor readability and losing the guarantee. Treat that as a behaviour change and test it with two sessions.
Verification
Concurrency behaviour needs a concurrent test. The companion example starts two connections, holds the first transaction open, starts the second in a thread, commits the first and records the second's outcome, for both statements and both isolation levels. It needs a disposable PostgreSQL server reachable through a DSN in an environment variable; without one, its offline tests check the SQL text and the retry logic with a fake connection. Run the concurrent test against the PostgreSQL version you deploy, because the documented guarantees are what you rely on, and the test tells you whether your code relies on anything more.