Tutorials SQL Server Mastery

Locking & Blocking: Analyzing Deadlocks like a Pro

On this page

Locking & Deadlocks

Locking is the mechanism SQL Server uses to ensure data integrity. Blocking is normal—it means one user is waiting for another to finish. Deadlocking is an error—it means User A is waiting for User B, and User B is waiting for User A. They are stuck forever until SQL Server kills one of them.

1. Shared (S) vs Exclusive (X) Locks

  • Shared Lock: Acquired for Read operations. Multiple users can hold Shared locks on the same row.
  • Exclusive Lock: Acquired for Write operations. Only one user can hold an Exclusive lock. It blocks everyone else.

2. The Deadlock Graph

When a deadlock occurs, SQL Server chooses a Deadlock Victim (usually the transaction that is easiest to roll back) and throws an error. As an architect, you should use the profiler or extended events to capture the Deadlock Graph, which visually shows you which tables and indexes were involved in the collision.

4. Interview Mastery

Q: "How can I prevent deadlocks in my application code?"

Architect Answer: "The most effective way is to **Access Tables in the same order** everywhere in your app. If Procedure A updates 'Users' then 'Orders', and Procedure B updates 'Orders' then 'Users', they will eventually deadlock. If both always do 'Users' then 'Orders', they will simply block and wait for each other, which is much safer. Also, keeping transactions as short as possible reduces the 'Window of Collision'."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

SQL Server Mastery
Course syllabus
1. SQL Server Architecture & Basics
2. Advanced T-SQL Querying
3. Indexing & Performance Tuning
4. Database Programmability
5. Transactions & Concurrency
6. Administration & Security
7. Modern SQL & Cloud
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details