Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
SQL

SQL Server: Fix a Deadlock Between Two Identical Merge Statements

- 27.11.26 - ErcanOPAK

🗄️ 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 to SERIALIZABLE specifically 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 (Sku here) — MERGE without 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_getapplock around the batch, or switching to separate UPDATE-then-INSERT WHERE NOT EXISTS statements, which can take narrower, more predictable locks than a single combined MERGE.

🚨 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.

— Database Engineer

Related posts:

SQL: Use Primary Keys for Data Uniqueness

SQL: Use Primary Keys for Data Uniqueness

SQL Server: Fix a Query That Returns Different Row Counts Depending on the Session's Isolation Level

SQL Server: Fix a Query That Returns Different Row Counts Depending on the Session's Isolation Level

The Hidden Killer: Scalar Functions — How to Avoid Massive Slowdowns

The Hidden Killer: Scalar Functions — How to Avoid Massive Slowdowns

Views: 7
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Windows 11: Fix File Copy Progress Freezing on Large Transfers
Kubernetes: Fix an HPA Ignoring Custom Metrics From the Adapter

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,080 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 672 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 631 views
  8. 08Average of all values in a column that are not zero in SQL 585 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 562 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com