Two overlapping runs of a PostgreSQL product-feed sync both use MERGE ... WHEN NOT MATCHED THEN INSERT, and one fails with SQLSTATE 23505; why, and would INSERT ... ON CONFLICT avoid it?
answer
- decided against a snapshot
- the join missed an uncommitted row
- MERGE does not restart
- arbiter-driven insert-or-update
basics
~20 sMERGE picks MATCHED or NOT MATCHED by joining against its snapshot, so a row the other run inserts concurrently is invisible, the INSERT arm fires, and the unique index raises 23505. ON CONFLICT DO UPDATE would have updated that row instead.
solid answer
~50 sUnder read committed, `MERGE` classifies each source row by its join against the statement's snapshot. If the other sync run has inserted the same `(supplier_id, supplier_sku)` but not yet committed, or committed after this snapshot, the join finds nothing, the `WHEN NOT MATCHED` `INSERT` runs, waits on the unique index and then fails with `23505`; the manual says `MERGE` does not restart evaluation of the `MATCHED` conditions. `INSERT ... ON CONFLICT DO UPDATE` works from the arbiter index itself and guarantees insert-or-update even when the conflicting row is invisible to its snapshot. So yes for the upsert part — but `MERGE` alone gives `WHEN NOT MATCHED BY SOURCE` (17+) for delisting and multiple conditional arms. Typical fixes: upsert with `ON CONFLICT` plus a separate delist statement, retry `MERGE` on `23505`, or stop sync runs overlapping.
code
sql · 16 linesBEGIN;
INSERT INTO catalog_product AS p (supplier_id, supplier_sku, title, price, stock)
SELECT supplier_id, supplier_sku, title, price, stock FROM feed_staging
ON CONFLICT (supplier_id, supplier_sku) DO UPDATE
SET price = EXCLUDED.price, stock = EXCLUDED.stock, delisted = false;
UPDATE catalog_product p
SET delisted = true
WHERE p.supplier_id = 42
AND NOT p.delisted
AND NOT EXISTS (SELECT 1 FROM feed_staging s
WHERE s.supplier_id = p.supplier_id
AND s.supplier_sku = p.supplier_sku);
COMMIT;go deeper
Know that MERGE and ON CONFLICT both upsert but behave differently when two sessions insert the same key at once.
Explain that MERGE chooses MATCHED or NOT MATCHED from a join against its snapshot, while ON CONFLICT lets the unique index detect the conflict.
Diagnose the 23505 from overlapping runs, cite the no-restart rule, and pick a fix: split upsert and delist, bounded retry, or single-flight scheduling.
Decide whether one expressive MERGE is worth its weaker guarantee for this pipeline, and how job scheduling and idempotency remove the race at its source.
## The incident The catalogue sync is scheduled hourly, but one run overran and the next started while it was still working. Both executed: ```sql MERGE INTO catalog_product p USING feed_staging s ON p.supplier_id = s.supplier_id AND p.supplier_sku = s.supplier_sku WHEN MATCHED THEN UPDATE SET price = s.price, stock = s.stock WHEN NOT MATCHED THEN INSERT (supplier_id, supplier_sku, title, price, stock) VALUES (s.supplier_id, s.supplier_sku, s.title, s.price, s.stock); ``` One of them failed with `ERROR: duplicate key value violates unique constraint` — SQLSTATE `23505`, `unique_violation` — on a brand-new SKU. ## Why MERGE raised 23505 `MERGE` is a join between source and target followed by per-row actions. Whether a source row is **MATCHED** is decided by that join, evaluated against the statement's **snapshot** (read committed takes a fresh one per statement). 1. Run A inserts SKU `ACME-2001` and has not committed, or commits after run B's snapshot. 2. Run B's join cannot see that row, so `ACME-2001` is **NOT MATCHED**. 3. Run B attempts the `INSERT`. The unique index check finds A's entry, waits for A to finish, and when A commits raises `23505`. The manual's concurrency section is explicit: if `MERGE` attempts an `INSERT` and a duplicate is concurrently inserted, a uniqueness violation is raised, and `MERGE` **does not** restart evaluation of the `MATCHED` conditions. Its other concurrency rules are more forgiving: when a matched row is **concurrently updated** and still joins, `MERGE` re-evaluates the `WHEN` conditions on the new version from the first action; if the update makes the join fail, it falls through to the `NOT MATCHED` actions; if the row is concurrently **deleted**, it evaluates the `NOT MATCHED [BY TARGET]` actions. ## Why ON CONFLICT does not `INSERT ... ON CONFLICT DO UPDATE` does not decide by joining. It **attempts the insert** and lets the arbiter unique index detect the conflict; on a conflict it updates the existing row. The manual guarantees an atomic insert-or-update outcome barring unrelated errors, and notes that under read committed the update may hit a row of which **no version is conventionally visible** to the command's snapshot. Run B would have waited for run A and then updated A's row. ## The trade-off | Need | `INSERT ... ON CONFLICT` | `MERGE` | |---|---|---| | Insert-or-update safe under concurrency | yes | no — `23505` possible | | Requires a unique index or constraint | yes (arbiter) | no, any join condition | | Delete or update target rows missing from the source | no | `WHEN NOT MATCHED BY SOURCE` (17+) | | Several conditional actions, `DELETE`, `DO NOTHING` | `DO NOTHING` or one `DO UPDATE` | yes | | Per-row action in `RETURNING` | 18's `old`/`new` | `merge_action()` (17+) | | Same key twice in the input | `21000` | `21000` for repeated update/delete, `23505` for repeated insert | The manual itself says the two statements have differences and restrictions and are **not interchangeable**. ## Recognising it in production - The failing run logs a `23505` on the supplier key for a SKU that was new in this hour's feed, never for an old one. - It appears only when runs overlap — after a slow run, a retry, or a second scheduler instance — which is why it looks intermittent. - The surviving run's rows are correct; the failed run rolled back entirely, so its updates to *existing* products were lost too and must be re-applied. ## What to do in the sync - **Split the statement**: upsert with `INSERT ... ON CONFLICT (supplier_id, supplier_sku) DO UPDATE`, then delist missing SKUs with a separate `UPDATE ... WHERE NOT EXISTS (...)`, in one transaction. - **Keep MERGE and retry**: catch `23505` and re-run the statement, which then sees the committed row as MATCHED. - **Stop the overlap**: make the job single-flight — the locking mechanics for that, such as an advisory lock, belong with PostgreSQL's locking material. - **Order the source** with an ordered `source_query`; the manual notes a consistent order may be needed to avoid deadlocks between concurrent `MERGE`s. Under repeatable read or serializable both statements raise serialization failures instead; that is a subject for PostgreSQL's isolation levels.
- Why does the MERGE above restrict WHEN NOT MATCHED BY SOURCE with p.supplier_id = 42?`NOT MATCHED BY SOURCE` fires for every target row with no source partner. The source is filtered to supplier 42, so without the extra condition every other supplier's products would be delisted too. Restricting the arm to the supplier being synced keeps the action inside the feed's scope.
- If you keep MERGE, is retrying on 23505 enough?For read committed, usually: the retried statement takes a new snapshot, sees the committed row as `MATCHED` and updates it. Bound the retries, and roll back to a savepoint or restart the transaction first, because the error aborts the current one. Retrying does not cure a source that holds the same key twice — that fails every time and must be deduplicated.
- Does ON CONFLICT DO UPDATE remove all concurrency errors from the sync?No. It removes the insert-versus-update race on the arbiter key, but two runs can still deadlock if they lock the same rows in different orders, a collision on a different unique index still raises `23505`, and under repeatable read a conflict with an invisible row raises a serialization failure.
- MERGE locks the whole key range, so a concurrent insert of the same SKU must wait and then match.
- On a unique violation MERGE automatically retries the row as WHEN MATCHED.
- MERGE and INSERT ... ON CONFLICT are interchangeable spellings of the same upsert.
- ON CONFLICT DO UPDATE makes deadlocks between overlapping runs impossible.
- Running MERGE under REPEATABLE READ turns the 23505 into a silent update.