Sub topic 8
MERGE under concurrent writes
This chapter assumes PostgreSQL 15 or later, basic transactions, primary keys, unique constraints, and the MERGE syntax from earlier chapters. The examples use an inventory target table with a primary key on product_id.
A MERGE statement makes decisions from a source set and a target table. Under the default READ COMMITTED isolation level, PostgreSQL normally gives the statement one snapshot of committed data. The statement uses that snapshot to decide whether each source row is matched or not matched.
Concurrent transactions can change the target after that decision. PostgreSQL then has to reconcile the original decision with the newer row version.
What happens when a matched row changes
Suppose a source row matches an inventory row. While MERGE waits for a lock held by another transaction, that transaction might update or delete the target row.
After the other transaction finishes, PostgreSQL can recheck the applicable WHEN MATCHED condition against the newer row version. This means a condition that was true at first might become false:
MERGE INTO inventory AS t
USING inventory_updates 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 THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);For example, another transaction might change quantity while this statement waits. PostgreSQL evaluates the WHEN clauses in their written order after the conflict is resolved. Clause ordering and conditions therefore matter even when the original snapshot suggested a different action.
If the concurrent transaction deletes the target row, the source row may become not matched. PostgreSQL can then use a suitable WHEN NOT MATCHED action. The result depends on the exact timing, the join condition, and the available clauses.
This behavior does not mean that MERGE locks every target row before it starts. It locks rows as it needs to perform their actions.
Why a unique violation can still occur
MERGE is not always an atomic upsert. Consider two transactions that run the same statement for a product that does not yet exist:
MERGE INTO inventory AS t
USING (
VALUES (3, 'washer', 40)
) AS s(product_id, name, delta)
ON t.product_id = s.product_id
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);The following timeline is possible:
| Transaction A | Transaction B |
|---|---|
| Sees no row for product 3 | Sees no row for product 3 |
| Attempts to insert product 3 | Attempts to insert product 3 |
| Inserts and commits | Waits, then receives a unique-violation error |
Both statements can decide that the source row is not matched because neither statement saw the other transaction's uncommitted insert. The primary key correctly prevents two rows with product_id = 3, but the second MERGE does not automatically turn that conflict into an update.
A typical error looks like this:
ERROR: duplicate key value violates unique constraint "inventory_pkey"The exact result can differ if one transaction rolls back or if the statements use different isolation levels.
Choosing a safer concurrency strategy
Use INSERT ... ON CONFLICT when the operation is fundamentally an insert-or-update operation and the conflict target is a unique constraint:
INSERT INTO inventory (product_id, name, quantity)
SELECT product_id, name, delta
FROM inventory_updates
ON CONFLICT (product_id) DO UPDATE
SET quantity = inventory.quantity + EXCLUDED.quantity,
updated_at = now();ON CONFLICT is designed to handle a uniqueness conflict during insertion. It is usually the simpler choice for a high-contention upsert.
Use MERGE when the source-to-target comparison needs several actions or business rules, such as conditional deletion, different updates, and insertion in one statement. Then decide how the application handles concurrent conflicts.
Common strategies include:
- Catch a unique-violation error and retry the whole transaction.
- Use
SERIALIZABLEisolation when the operation must behave as if transactions ran one at a time. - Lock relevant existing rows before the
MERGEwhen the rows already exist. - Use an application-level or advisory lock when transactions can race to create the same missing key.
SERIALIZABLE does not make conflicts disappear. PostgreSQL may instead raise a serialization failure, and the application must retry the transaction:
BEGIN;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
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);
COMMIT;The retry must include BEGIN, the isolation setting, the MERGE, and COMMIT. Retrying only the failed statement can leave the transaction unusable or omit other work that must be repeated together.
Exercise
Two transactions run a MERGE that inserts product 7 when it is missing. Both initially see no product 7. What should the application do if the second transaction receives a unique-violation error?
Show answer
Roll back and retry the complete transaction, or use INSERT ... ON CONFLICT when the required behavior is a simple insert-or-update.