Deadlock Prevention — Complete Guide
Deadlock Prevention — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of SQL Server Tutorial on Toolliyo Academy.
On this page
SQL Server Tutorial · Lesson 58 of 100
Deadlock Prevention
SQL basics ✓ → Queries → Advanced
Queries · 2 — JOINs · ~10 min · SQL — Transactions & Concurrency
What is this?
Prevent deadlocks by locking resources in one global order, keeping transactions short, and reducing lock footprint (indexes, RCSI where appropriate).
Why should you care?
Retries help, but prevention stops customer-facing failures.
See it live — copy this example
Run in SQL Server Management Studio (SSMS) or Azure Data Studio.
USE DataVerse;
CREATE OR ALTER PROCEDURE dbo.usp_TransferOrdered
@FromId INT, @ToId INT, @Amount DECIMAL(18,2)
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
DECLARE @First INT = CASE WHEN @FromId < @ToId THEN @FromId ELSE @ToId END;
DECLARE @Second INT = CASE WHEN @FromId < @ToId THEN @ToId ELSE @FromId END;
BEGIN TRAN;
UPDATE dbo.Accounts WITH (UPDLOCK, ROWLOCK) SET Balance = Balance WHERE AccountId = @First;
UPDATE dbo.Accounts WITH (UPDLOCK, ROWLOCK) SET Balance = Balance WHERE AccountId = @Second;
UPDATE dbo.Accounts SET Balance = Balance - @Amount WHERE AccountId = @FromId;
UPDATE dbo.Accounts SET Balance = Balance + @Amount WHERE AccountId = @ToId;
COMMIT;
END
What happened?
- Regardless of transfer direction, locks are acquired by ascending AccountId first.
- That removes the classic deadlock cycle between two transfers.
Practice next
- Create usp_TransferOrdered.
- Run concurrent transfers in opposite directions in lab.
- Compare to unordered locking.
- Remove the ordered pre-lock and try to reproduce deadlock.
- Log victims to an audit table.
Remember
One lock order for all writers. Short transactions. Retry as backup, not the only strategy.
Ordered account locks
All DataVerse money procs lock by AccountId ASC.
Outcome: Deadlock rate collapses under load tests.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!