🗄️ SQL Server: Fix a Deadlock Between Two Identical Merge Statements
Two sessions running the exact same MERGE statement against the same table, each upserting a different set of rows, can still deadlock on each other — MERGE takes both a range lock for its matching scan and an update/insert lock for the rows it actually changes, and under the default READ COMMITTED isolation those two lock types can be acquired in an order that lets two concurrent sessions each hold what the other one needs next.
🔎 The Problem
MERGE INTO Inventory AS target USING (VALUES (@Sku, @Qty)) AS src(Sku, Qty) ON target.Sku = src.Sku WHEN MATCHED THEN UPDATE SET Qty = src.Qty WHEN NOT MATCHED THEN INSERT (Sku, Qty) VALUES (src.Sku, src.Qty); -- Two sessions, different @Sku values, same statement, same table: -- Msg 1205: Transaction was deadlocked on lock resources...
âś… Fix: Reduce Lock Scope and Serialize the Hot Path
- Add
WITH (HOLDLOCK)or raise the statement’s isolation toSERIALIZABLEspecifically for the MERGE’s target table hint — counterintuitively, a stricter isolation level here often prevents the deadlock by forcing one session to wait cleanly instead of both acquiring partial locks. - Ensure there’s a unique index on the join key (
Skuhere) —MERGEwithout one can take a wider range lock than necessary to find matching rows, which is frequently the real source of the overlapping lock footprint. - For genuinely high-concurrency upsert paths, consider serializing access with
sp_getapplockaround the batch, or switching to separateUPDATE-then-INSERT WHERE NOT EXISTSstatements, which can take narrower, more predictable locks than a single combinedMERGE.
🚨 Why This Is Dangerous
- A deadlock victim’s transaction rolls back silently unless the calling application explicitly retries on error 1205 — without that retry logic, an upsert that should have succeeded just vanishes, and the inventory count it was supposed to update stays wrong.
MERGE looks like one atomic statement, but under the hood it’s still taking locks in steps — and two sessions can each finish a different step first.



