🧠 SQL Server Deadlocks Explained (Causes, Detection & Prevention)

Deadlocks are one of the most feared issues in SQL Server production environments. They don’t always appear in development, but when they hit production, they can freeze applications, fail transactions, and frustrate users.

This blog explains what deadlocks are, why they occur, and how to prevent them effectively.


1️⃣ What Is a Deadlock in SQL Server?

A deadlock occurs when:

  • Session A locks Resource 1 and waits for Resource 2
  • Session B locks Resource 2 and waits for Resource 1

πŸ‘‰ SQL Server resolves this by killing one session (deadlock victim).


2️⃣ Deadlock Error Message

❌ Error Message

Msg 1205, Level 13, State 51
Transaction (Process ID xx) was deadlocked on lock resources with another process and has been chosen as the deadlock victim.

3️⃣ Simple Deadlock Example

Session 1

BEGIN TRAN;
UPDATE Accounts SET Balance = Balance - 100 WHERE Id = 1;
-- waits
UPDATE Accounts SET Balance = Balance + 100 WHERE Id = 2;
COMMIT;

Session 2

BEGIN TRAN;
UPDATE Accounts SET Balance = Balance - 50 WHERE Id = 2;
-- waits
UPDATE Accounts SET Balance = Balance + 50 WHERE Id = 1;
COMMIT;

πŸ“Œ Both sessions wait on each other β†’ deadlock


4️⃣ Common Causes of Deadlocks

βœ” Different order of table access
βœ” Long-running transactions
βœ” Missing indexes
βœ” Cursor usage
βœ” User-defined functions inside transactions


5️⃣ How SQL Server Chooses Deadlock Victim

SQL Server selects:

  • Transaction with the lowest cost
  • Transaction with the lowest rollback impact

The killed session receives error 1205.


6️⃣ How to Detect Deadlocks

πŸ” Method 1: SQL Server Error Log

EXEC xp_readerrorlog;

πŸ” Method 2: Extended Events (Recommended)

Use:

  • xml_deadlock_report

πŸ” Method 3: SQL Server Profiler (Old)

Not recommended for production.


7️⃣ How to Prevent Deadlocks


βœ… 1. Access Objects in Same Order

Always update tables in a consistent order.


βœ… 2. Keep Transactions Short

❌ Avoid user input inside transactions
❌ Avoid delays


βœ… 3. Use Proper Indexes

Indexes reduce lock duration and scope.


βœ… 4. Use SET DEADLOCK_PRIORITY

SET DEADLOCK_PRIORITY LOW;

Lower priority session will be killed first.


βœ… 5. Use Snapshot Isolation (When Possible)

ALTER DATABASE MyDB
SET READ_COMMITTED_SNAPSHOT ON;

Reduces read locks.


8️⃣ Handling Deadlocks in Stored Procedures

βœ… Retry Logic Example

DECLARE @Retry INT = 3;

WHILE @Retry > 0
BEGIN
    BEGIN TRY
        EXEC dbo.TransferAmount;
        BREAK;
    END TRY
    BEGIN CATCH
        IF ERROR_NUMBER() = 1205
            SET @Retry = @Retry - 1;
        ELSE
            THROW;
    END CATCH
END

9️⃣ Deadlocks vs Blocking

BlockingDeadlock
Temporary waitPermanent wait
Eventually resolvesOne session killed
Normal behaviorError condition

πŸ”Ÿ Deadlock Best Practices Checklist

βœ” Use consistent object order
βœ” Keep transactions short
βœ” Avoid cursors
βœ” Index foreign keys
βœ” Handle error 1205
βœ” Monitor deadlocks


πŸ“Œ Deadlock-Safe Stored Procedure Template

CREATE PROCEDURE dbo.SafeTransfer
    @FromId INT,
    @ToId INT,
    @Amount DECIMAL(10,2)
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        BEGIN TRANSACTION;

        UPDATE Accounts SET Balance = Balance - @Amount WHERE Id = @FromId;
        UPDATE Accounts SET Balance = Balance + @Amount WHERE Id = @ToId;

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        THROW;
    END CATCH
END

✍️ Conclusion

Deadlocks are not bugs; they are design problems. With correct transaction design, indexing, and error handling, most deadlocks can be completely avoided.

Understanding deadlocks makes you production-ready as a SQL Server developer.

Leave a Comment

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

Scroll to Top