What Is a SQL Server Deadlock? Why Database Deadlocks Happen and How to Fix Them

What Is a SQL Server Deadlock? Why Database Deadlocks Happen and How to Fix Them

What is a SQL Server deadlock?

In databases where many users perform operations concurrently, locking is necessary to maintain data consistency.

A deadlock occurs when two or more transactions each hold a resource that another transaction needs and they begin waiting for each other.

In simple terms:

Transaction A is waiting for a resource locked by Transaction B, while Transaction B is simultaneously waiting for a resource locked by Transaction A.

A simple deadlock example

Consider two tables:

Customers --------- Id Name Balance Orders ------ Id CustomerId Status 

The first transaction updates Customers and then Orders:

BEGIN TRANSACTION; UPDATE Customers SET Balance = Balance - 100 WHERE Id = 1; WAITFOR DELAY '00:00:05'; UPDATE Orders SET Status = 'Paid' WHERE Id = 10; COMMIT; 

The second transaction uses the opposite order:

BEGIN TRANSACTION; UPDATE Orders SET Status = 'Processing' WHERE Id = 10; WAITFOR DELAY '00:00:05'; UPDATE Customers SET Balance = Balance + 100 WHERE Id = 1; COMMIT; 

If they execute concurrently, the following cycle may occur:

Transaction A locks Customers ↓ waits for Orders ↑ │ Transaction B locks Orders ↓ waits for Customers 

What does SQL Server do when a deadlock occurs?

SQL Server detects deadlock cycles and prevents the transactions from waiting forever.

It chooses one transaction as the deadlock victim, rolls that transaction back and allows the other transaction to continue.

A typical error is:

Transaction was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction. 

Deadlock vs Blocking

Blocking and deadlocking are related but different.

Blocking

One transaction waits for another transaction to release a lock. Once the first transaction finishes, the waiting transaction can continue.

Deadlock

The transactions form a circular dependency and cannot continue unless one is terminated.

Common causes of deadlocks

  • Accessing tables in different orders
  • Long-running transactions
  • Missing or inefficient indexes
  • Locking too many rows
  • Waiting for external APIs inside a transaction
  • Unnecessarily strict isolation levels
  • Heavy concurrent updates to the same resources

1. Use a consistent resource access order

One of the most effective ways to reduce deadlocks is to ensure that different parts of the application access shared resources in the same order.

Instead of:

Process 1: Customers → Orders Process 2: Orders → Customers 

prefer a consistent convention:

Customers → Orders → Payments 

2. Keep transactions short

The longer a transaction remains open, the longer its locks may remain active.

Avoid performing slow external operations while a database transaction is open.

3. Missing indexes can increase deadlock risk

A missing index does not automatically create a deadlock, but it may force SQL Server to scan significantly more data.

This can increase the number of locked rows or pages and therefore increase contention.

For example:

UPDATE Orders SET Status = 'Cancelled' WHERE CustomerId = 500; 

A suitable index might be:

CREATE INDEX IX_Orders_CustomerId ON Orders(CustomerId); 

4. Analyze the Deadlock Graph

A deadlock graph can show:

  • The statements involved in the deadlock
  • The resources held by each transaction
  • The resources each transaction was waiting for
  • The transaction selected as the victim

Modern SQL Server installations can capture deadlock information through Extended Events, including the default system_health session.

5. Review transaction isolation levels

Common SQL Server isolation levels include:

  • READ UNCOMMITTED
  • READ COMMITTED
  • REPEATABLE READ
  • SNAPSHOT
  • SERIALIZABLE

Higher isolation levels may hold more locks or hold them for longer periods. Changing isolation levels should therefore be done carefully.

READ_COMMITTED_SNAPSHOT

For some workloads, READ_COMMITTED_SNAPSHOT can reduce blocking between readers and writers by using row versioning.

ALTER DATABASE MyDatabase SET READ_COMMITTED_SNAPSHOT ON; 

This does not eliminate every type of deadlock and should be evaluated against application behavior and tempdb requirements.

6. Implement retries for transient deadlocks

Even a well-designed high-concurrency system may occasionally experience a deadlock.

SQL Server typically reports a deadlock victim using error number:

1205 

A .NET application can retry that operation carefully:

for (int attempt = 1; attempt <= 3; attempt++) { try { await SaveOrderAsync(); break; } catch (SqlException ex) when (ex.Number == 1205) { if (attempt == 3) throw; await Task.Delay(200 * attempt); } } 

In production systems, an exponential backoff strategy is often more appropriate.

Retry is not the root-cause fix

If deadlocks happen frequently, simply retrying the transactions can hide a deeper database problem.

The better approach is:

Detect Deadlock ↓ Analyze Deadlock Graph ↓ Find Root Cause ↓ Fix Access Pattern / Index / Transaction ↓ Use Retry for Rare Remaining Cases 

Can SELECT statements participate in deadlocks?

Yes.

Depending on the isolation level, execution plan and lock hints, SELECT statements may also participate in deadlock cycles.

Lock hints such as UPDLOCK should therefore be used only when their behavior is fully understood.

Is NOLOCK a deadlock solution?

No.

NOLOCK can reduce some blocking scenarios, but it introduces the possibility of dirty reads and inconsistent results.

It should not be treated as a general performance or deadlock solution.

Deadlock Priority

SQL Server allows a transaction to influence how likely it is to be selected as the deadlock victim:

SET DEADLOCK_PRIORITY LOW; 

This controls victim selection behavior but does not remove the underlying cause of the deadlock.

Split very large operations when appropriate

Large updates can hold locks for long periods and may contribute to lock escalation.

When business rules allow it, batch processing can reduce the scope of each transaction:

WHILE 1 = 1 BEGIN UPDATE TOP (1000) Orders SET Archived = 1 WHERE OrderDate < '2023-01-01' AND Archived = 0; IF @@ROWCOUNT = 0 BREAK; END 

Deadlock troubleshooting checklist

  1. Capture the deadlock graph.
  2. Identify the statements involved.
  3. Check the order in which resources are accessed.
  4. Review transaction duration.
  5. Inspect execution plans.
  6. Check relevant indexes.
  7. Review large UPDATE and DELETE statements.
  8. Inspect isolation levels and lock hints.
  9. Move external work outside transactions when possible.
  10. Add controlled retries for transient cases.

Conclusion

SQL Server deadlocks are an important concurrency problem in multi-user systems, but they can usually be understood and reduced systematically.

The most important practices are:

  • Access resources in a consistent order.
  • Keep transactions as short as possible.
  • Use appropriate indexes.
  • Analyze deadlock graphs instead of guessing.
  • Avoid unnecessary lock hints.
  • Retry rare transient deadlocks safely.

When investigating a deadlock, do not only ask: “Which query failed?”

“Which resources did these transactions lock, and in what order?”

That question usually leads much closer to the actual solution.

//

0 Comments

Write Comment

E-Mail address will not be published