A deadlock happens when two or more transactions wait for each other to release locks, so none can continue. This causes the system to freeze those transactions until resolved.
Transaction 1 locks Table A then Table B.
Transaction 2 locks Table B then Table A.
Which option shows the order of locking that can cause a deadlock?
Deadlocks occur when Transaction 1 locks Table A and waits for Table B, while Transaction 2 locks Table B and waits for Table A. Both wait forever.
In SQL Server, the correct syntax to set lock timeout is SET LOCK_TIMEOUT 5000; which sets timeout to 5000 milliseconds.
Accessing tables in the same order prevents circular waiting, which is a main cause of deadlocks.
Transaction 1:
BEGIN TRAN;
UPDATE Accounts SET balance = balance - 100 WHERE id = 1;
WAITFOR DELAY '00:00:05';
UPDATE Accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
Transaction 2:
BEGIN TRAN;
UPDATE Accounts SET balance = balance + 100 WHERE id = 2;
WAITFOR DELAY '00:00:05';
UPDATE Accounts SET balance = balance - 100 WHERE id = 1;
COMMIT;
What causes the deadlock here?
Transaction 1 locks account 1 then waits before locking account 2. Transaction 2 locks account 2 then waits before locking account 1. This causes a deadlock.
