SQL fundamentals learning path Level 2 This level · 4 of 7
Medium sql sql-server

What is the difference between blocking and a deadlock?

The 30 second answer

Blocking is a one-way wait: the second session proceeds once the first releases its lock. A deadlock is a wait-for cycle, so nobody can finish unless the engine aborts one transaction. SQL Server does that with error 1205; blocking does not resolve itself that way, and by default it can last until the holder commits, rolls back, or a lock timeout fires.

Could you say this in an interview?

Blocking is a one-way wait. If my transaction already holds a lock on a row, another transaction that needs a conflicting lock waits, then continues when I commit or roll back and release the lock. It has not done anything that stops me from finishing, so the wait can end on its own. By default SQL Server transactions do not time out unless LOCK_TIMEOUT is set.

A deadlock is a cycle. Two sessions each hold a lock the other needs, so both wait forever unless an outside process breaks the cycle. A typical case is two seat updates in opposite order: I lock seat C7 and then need C8, while another transaction has already locked C8 and now needs C7. Deadlocking is often confused with ordinary blocking; the difference is that a deadlock cannot complete without a victim.

-- session 1
BEGIN TRANSACTION;
UPDATE Seats SET Status = 'Held' WHERE Id = 'C7';
UPDATE Seats SET Status = 'Held' WHERE Id = 'C8';
COMMIT;

-- session 2, at the same time, opposite order: this is a deadlock, not plain blocking
BEGIN TRANSACTION;
UPDATE Seats SET Status = 'Held' WHERE Id = 'C8';
UPDATE Seats SET Status = 'Held' WHERE Id = 'C7';
COMMIT;
Sources (2)
  1. Microsoft Learn — Deadlocks Guidelearn.microsoft.com
  2. Microsoft Learn — MSSQLSERVER_1205learn.microsoft.com
Previous
Next