The 30 second answer
Yes. In REPEATABLE READ or SERIALIZABLE, two sessions can each take a shared lock on the same row, then both try to convert it to exclusive for an update. Neither conversion can proceed, which is a conversion deadlock. I prevent it by reading with UPDLOCK: only one session can hold an update lock on the resource, so the second waits from the start and no cycle forms.
Yes. A cycle does not require two different rows. Under REPEATABLE READ or SERIALIZABLE, a read keeps its shared (S) lock until the transaction ends. If two sessions both read the same row, they both hold S. Each then tries to update the row, which needs an exclusive (X) lock. X is not compatible with the other session's S, so both sit in an S to X conversion and wait for each other. That is a conversion deadlock. It is much less likely in default READ COMMITTED, where shared locks are released as soon as the read finishes, but the pattern can still appear if the read and the update are separate statements.
The fix is to acquire an update (U) lock on the read that I intend to follow with an update, using WITH (UPDLOCK). U is compatible with S, but only one transaction can hold a U lock on a resource. The second session waits up front instead of both taking S and later getting stuck. When the first session updates the row, its U lock converts to X without a cycle. I have to use UPDLOCK on every path that reads the row with the intent to update it; a path that still starts with a shared lock can reintroduce the deadlock.
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
BEGIN TRANSACTION;
SELECT Status FROM Seats WITH (UPDLOCK) WHERE Id = 'C7';
-- a second session now waits here, instead of both holding S and then deadlocking on S to X
UPDATE Seats SET Status = 'Sold' WHERE Id = 'C7';
COMMIT;
Sources (2)
- Microsoft Learn — Transaction Locking and Row Versioning Guidelearn.microsoft.com
- Microsoft Learn — Table Hints (UPDLOCK)learn.microsoft.com