The 30 second answer
I cannot reduce deadlocks to zero, but I can make them rare. I make every transaction lock objects in the same order, keep transactions short and free of user interaction, and use a selective index so a query locks fewer rows than a scan would. I also avoid REPEATABLE READ or SERIALIZABLE unless I need them, and I consider READ_COMMITTED_SNAPSHOT so readers do not take shared locks on the data.
The docs are explicit that deadlocks cannot be completely avoided; the goal is to minimize them and to handle the ones that remain. I start with a consistent lock order. If every transaction updates seat C7 and then C8, one session may block the other on C7, but no cycle forms, and the waiter proceeds when the first transaction finishes.
I also keep transactions short and in one batch, and I never wait for a user inside an open transaction, because locks are held until commit or rollback. A useful index matters for the same reason: locking many rows has a higher chance of colliding with another session, and a scan or an unselective plan can lock far more keys than a seek on the rows the query actually needs. A seek is not "one lock"; it still locks each qualifying key.
I avoid REPEATABLE READ and SERIALIZABLE unless the isolation is required, because those levels hold shared locks until the end of the transaction. For read/write contention, Microsoft recommends row-versioned READ COMMITTED by enabling READ_COMMITTED_SNAPSHOT, so statements read a committed snapshot and do not take shared locks on the data rows.
-- both sessions use the same order, so this becomes blocking, not a deadlock
BEGIN TRANSACTION;
UPDATE Seats SET Status = 'Held' WHERE Id = 'C7';
UPDATE Seats SET Status = 'Held' WHERE Id = 'C8';
COMMIT;
Sources (3)
- Microsoft Learn — Deadlocks Guidelearn.microsoft.com
- Microsoft Learn — Transaction Locking and Row Versioning Guidelearn.microsoft.com
- Microsoft Learn — MSSQLSERVER_1205learn.microsoft.com