Menu

How to Fix SQL Server Deadlocks: Causes, Detection and Real Fixes
📰

How to Fix SQL Server Deadlocks: Causes, Detection and Real Fixes

DEV Community: database·LingamSuyambu·10 days ago
#ktuDDyLG
#devtodatabase#devto#dev#deadlock#article
Reading 0:00
15s threshold

Originally published at SQL & Cloud Lab .

A deadlock happens when two sessions each hold a lock the other one needs. Neither can continue, so SQL Server picks one as the victim , rolls its transaction back and raises error 1205 . The other session carries on. Occasional deadlocks are normal in busy systems; frequent ones point to a fixable pattern in your code or indexes.

What a deadlock looks like

The classic example is two transactions updating the same two rows in opposite order:

-- Session 1 BEGIN TRAN ; UPDATE dbo . Account SET Balance -= 100 WHERE AccountId = 1 ; UPDATE dbo . Account SET Balance += 100 WHERE AccountId = 2 ; COMMIT ;

-- Session 2 (runs at the same time) BEGIN TRAN ; UPDATE dbo . Account SET Balance -= 50 WHERE AccountId = 2 ; UPDATE dbo . Account SET Balance += 50 WHERE AccountId = 1 ; COMMIT ;

Enter fullscreen mode

Exit fullscreen mode

Session 1 locks row 1 and waits for row 2. Session 2 locks row 2 and waits for row 1.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.