Sub topic 8
MERGE under concurrent writes
This chapter assumes you can write a basic MERGE with WHEN MATCHED and WHEN NOT MATCHED clauses. It also assumes you know what a unique index enforces, and that you can open two psql sessions to try the examples. The tables are inventory and inventory_updates from the earlier chapters. MERGE needs PostgreSQL 15 or later.
A single MERGE runs as one statement, but it is not magically isolated from other sessions. Another transaction can update, delete, or insert rows in the target while your statement runs. This chapter covers what PostgreSQL does in each case, which errors you should expect, and how to handle them.
What MERGE locks and what it does not
MERGE takes a ROW EXCLUSIVE table lock on the target. That is the same lock INSERT, UPDATE, and DELETE take, so it does not block other writers. It reads the source with ordinary read locks.
Row-level behavior is where the details are:
- When a
WHEN MATCHEDaction updates or deletes a target row, that row is locked until your transaction ends. Another writer that wants the same row waits. - When a
WHEN NOT MATCHEDaction inserts a row, there was no row to lock beforehand. Nothing stops another session from inserting the same key at the same moment.
That asymmetry causes most of the surprises below. Matched rows are protected by row locks, and missing rows are not protected by anything except a unique index, if you have one.
Setup
Reset the tables to the starting state from the first chapter so the examples behave the same way for you.
DROP TABLE IF EXISTS inventory_updates;
DROP TABLE IF EXISTS inventory;
CREATE TABLE inventory (
product_id int PRIMARY KEY,
name text NOT NULL,
quantity int NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE inventory_updates (
product_id int,
name text,
delta int
);
INSERT INTO inventory (product_id, name, quantity) VALUES
(1, 'bolt', 100),
(2, 'nut', 50);
INSERT INTO inventory_updates (product_id, name, delta) VALUES
(2, 'nut', 25),
(3, 'washer', 40);READ COMMITTED: re-checking a concurrently changed row
READ COMMITTED is the default isolation level. Each statement sees a snapshot taken when the statement starts. If MERGE reaches a target row that another transaction has changed since then, it cannot use its snapshot version of that row. It waits for the other transaction to finish and then acts on the result.
- The other transaction rolls back.
MERGEcarries on with the row as it was. - The other transaction commits an update, and the join condition still holds.
MERGEre-reads the new version of the row and applies its action to that version. - The other transaction commits an update, and the join condition no longer holds. The source row is treated as unmatched.
MERGEmoves on to theWHEN NOT MATCHEDclauses. - The other transaction commits a delete. The join also fails, so
MERGEmoves on to theWHEN NOT MATCHEDclauses.
Case 1: a concurrent update
Run these in two sessions, in the order shown by the comments.
-- Session A
BEGIN;
UPDATE inventory SET quantity = quantity - 10 WHERE product_id = 2;
-- quantity is now 40 inside this transaction, and the row is locked
-- Session B (blocks, waiting for A)
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);
-- Session A
COMMIT;Session B resumes after the commit. It sees quantity 40, not the 50 in its original snapshot, and writes 40 + 25 = 65. No update is lost, because t.quantity in the SET expression refers to the latest committed version of the row.
Conditions restart from the first clause
After a concurrent update, PostgreSQL does not simply run the action that matched before. It re-evaluates every WHEN condition on the new row version, starting from the first clause. The clause that wins may be a different one. Take the statement from the earlier chapter that deletes rows whose quantity reaches zero:
MERGE INTO inventory AS t
USING (
SELECT product_id, max(name) AS name, sum(delta) AS delta
FROM inventory_updates
GROUP BY product_id
) AS s
ON t.product_id = s.product_id
WHEN MATCHED AND t.quantity + s.delta <= 0 THEN
DELETE
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED AND s.delta > 0 THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);Suppose a concurrent transaction changes a row's quantity while this statement is waiting on it. When the lock is released, the DELETE condition is tested again against the new quantity. A row that was headed for the plain UPDATE may now be deleted, and the reverse can also happen. This is correct behavior: the decision is based on current data.
Case 2: a concurrent delete
-- Session A
BEGIN;
DELETE FROM inventory WHERE product_id = 2;
-- Session B (blocks on row 2)
MERGE INTO inventory AS t
USING inventory_updates AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);
-- Session A
COMMIT;When A commits, row 2 no longer exists. The join for source row (2, 'nut', 25) fails, so session B falls through to the WHEN NOT MATCHED clause and inserts a new row with quantity 25. If you had no WHEN NOT MATCHED clause, the source row would be skipped silently. Decide whether that is what you want. If a deleted row must not be resurrected, add a condition or a different design, such as soft deletes.
Concurrent inserts: the unique violation
Now the case that row locks cannot cover. Product 3 does not exist yet, and two sessions merge it at the same time.
-- Session A
BEGIN;
MERGE INTO inventory AS t
USING (VALUES (3, 'washer', 40)) AS s(product_id, name, delta)
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);
-- inserted product 3, not yet committed
-- Session B: same statement
-- Neither session can see the other's uncommitted row, so B also decides "not matched"
-- and tries to insert. The unique index on product_id makes B wait for A.
-- Session A
COMMIT;
-- Session B now fails:
-- ERROR: duplicate key value violates unique constraint "inventory_pkey"Session B does not go back and re-evaluate the join as a match. MERGE has already chosen its action for that source row. The unique index only prevents corrupt data, and it does not turn the INSERT into an UPDATE. If the table had no unique index, both inserts would succeed and you would have duplicate rows.
This is the main way MERGE differs from INSERT ... ON CONFLICT DO UPDATE. The ON CONFLICT form is built to resolve this race: it either inserts or updates, even under concurrency. MERGE makes no such promise. The PostgreSQL documentation says plainly that a MERGE with INSERT and UPDATE actions looks like ON CONFLICT but does not guarantee that one of them will happen.
Ways to handle the race
| Approach | How it works | Cost |
|---|---|---|
| Retry on `unique_violation` | Catch SQLSTATE `23505` and run the statement again. The row now exists, so the retry takes the `WHEN MATCHED` path. | Simple, and works at any concurrency level. Needs retry code. |
| Use `INSERT ... ON CONFLICT` | Let PostgreSQL resolve the race for plain insert-or-update. | Cannot delete, and has no per-row conditional branching like `MERGE`. |
| Take a table lock | `LOCK TABLE inventory IN SHARE ROW EXCLUSIVE MODE` before the `MERGE`. This blocks other writers, including other `MERGE`s. | Serializes all writers. Use it only for rare batch jobs. |
| Take an advisory lock | Use `pg_advisory_xact_lock(key)` so only one job at a time runs this merge. | Works only if all writers cooperate. |
A retry loop in PL/pgSQL looks like this. It runs as written on the setup tables:
DO $$
BEGIN
LOOP
BEGIN
MERGE INTO inventory AS t
USING (VALUES (3, 'washer', 40)) AS s(product_id, name, delta)
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);
EXIT; -- success, leave the loop
EXCEPTION WHEN unique_violation THEN
-- another session inserted the row first; loop and try again
NULL;
END;
END LOOP;
END
$$;The BEGIN ... EXCEPTION block creates a subtransaction. When the error occurs, only that attempt is rolled back, and the loop starts again. On the second pass, the row from the other session is visible and the WHEN MATCHED branch runs.
REPEATABLE READ and SERIALIZABLE: errors instead of re-checks
Under REPEATABLE READ and SERIALIZABLE, the whole transaction uses one snapshot. PostgreSQL cannot quietly switch MERGE to a newer row version, because that would break the snapshot guarantee. If MERGE needs to update or delete a row that a concurrent transaction changed and committed after the snapshot, it raises an error:
ERROR: could not serialize access due to concurrent updateThe same error occurs for a concurrent delete. The SQLSTATE is 40001. Your application should roll back and rerun the whole transaction, not just the failed statement. SERIALIZABLE can also raise 40001 for read/write dependency patterns that involve no single row, so the retry logic is needed there anyway.
| Isolation level | Concurrent update or delete of a matched row | Concurrent insert of the same new key |
|---|---|---|
| `READ COMMITTED` | Waits, re-checks conditions on the new version, continues. | Unique violation (`23505`) if a unique index exists. Duplicates if not. |
| `REPEATABLE READ` | Serialization failure (`40001`). | Unique violation (`23505`). |
| `SERIALIZABLE` | Serialization failure (`40001`). | Serialization failure or unique violation. Retry both. |
Deadlocks in batch merges
A MERGE that updates many rows locks them one at a time, in the order the executor produces them. Two MERGEs that touch overlapping rows in different orders can each hold a lock the other needs. PostgreSQL detects the cycle and aborts one with 40P01.
Ways to reduce the risk:
- Keep batches small, so locks are held for less time.
- Avoid running overlapping merges at the same time. A scheduler or an advisory lock can enforce this.
- Commit as soon as the merge finishes. Do not leave a transaction open after the
MERGEwhile the application does other work. - Retry on
40P01, the same way as for the other errors.
Sorting the source with ORDER BY can make the lock order more consistent, but the planner decides the join method, so do not treat this as a guarantee.
Checklist for concurrent use
- Make sure the columns in the
ONcondition have a unique index if you insert. Without it, concurrent inserts create duplicates and nothing raises an error. - Decide what a concurrently deleted row should mean. If the
WHEN NOT MATCHEDbranch would bring it back and that is wrong, add a condition to that clause. - Add retry handling for
23505,40001, and40P01. - If the workload is only insert-or-update, compare it with
INSERT ... ON CONFLICT, which handles the insert race without a retry loop. - Test with two real sessions. Concurrency bugs rarely appear in single-session tests.
Exercise
Session A runs BEGIN; DELETE FROM inventory WHERE product_id = 2; and has not committed. Session B runs a MERGE with WHEN MATCHED THEN UPDATE ... and WHEN NOT MATCHED THEN INSERT ... for product 2, at READ COMMITTED. Then A commits. What does B do, and why?
Show answer
B waits on the row lock until A commits. After the commit the row no longer exists, so the join fails for that source row. B then evaluates its WHEN NOT MATCHED clauses and inserts a new row for product 2. Without a WHEN NOT MATCHED clause, the source row would be skipped.
Exercise
Two READ COMMITTED sessions run the same MERGE for product 3, which does not exist. Session B fails with a unique violation. Why did MERGE not switch to the WHEN MATCHED branch, and what is the simplest application-level fix?
Show answer
Neither session could see the other's uncommitted insert, so both chose the WHEN NOT MATCHED action. MERGE does not re-run the join after the INSERT hits the unique index, so the second insert raises 23505. The simplest fix is to catch unique_violation and run the statement again. The row is then visible and the retry takes the WHEN MATCHED path. Using INSERT ... ON CONFLICT DO UPDATE is an alternative when no delete or conditional branching is needed.
Exercise
A MERGE running at REPEATABLE READ fails with SQLSTATE 40001 after waiting on a row updated by another transaction. Should the application retry only the MERGE statement or the whole transaction?
Show answer
The whole transaction. Under REPEATABLE READ the transaction keeps one snapshot, so rerunning only the failed statement would still use the old snapshot. Roll back and start a new transaction, ideally with a retry limit and a short delay.