SQL Server Deadlocks: How to Capture, Read and Fix Them

SQL Server 5 min readUpdated Oct 30, 2026
4 views0 comments

Users report random “Transaction was deadlocked on lock resources with another process and has been chosen as the deadlock victim” errors. This is error 1205. A deadlock is different from ordinary blocking: in blocking one session simply waits for another to finish, but in a deadlock two sessions each hold something the other needs, so neither can ever finish. SQL Server detects the cycle within seconds and kills one session (the victim) to let the other continue.

How a deadlock happens

Session 1                           Session 2
---------                           ---------
BEGIN TRAN                          BEGIN TRAN
UPDATE Accounts  (locks row A)      UPDATE Orders    (locks row B)
UPDATE Orders    (wants row B) ...  UPDATE Accounts  (wants row A) ...
        waits for Session 2   <->   waits for Session 1     => DEADLOCK

The classic cause: two transactions touch the same objects in opposite order.

Step 1: Reproduce one on a test database

It helps to see one on purpose. Use a test database, never production. Create two small tables:

CREATE TABLE dbo.TableA (id int PRIMARY KEY, val int);
CREATE TABLE dbo.TableB (id int PRIMARY KEY, val int);
INSERT dbo.TableA VALUES (1, 0);
INSERT dbo.TableB VALUES (1, 0);

Open two query windows. Run this in window 1, then within 10 seconds run the second script in window 2:

-- Window 1
BEGIN TRAN;
UPDATE dbo.TableA SET val = 1 WHERE id = 1;
WAITFOR DELAY '00:00:10';
UPDATE dbo.TableB SET val = 1 WHERE id = 1;
COMMIT;
-- Window 2
BEGIN TRAN;
UPDATE dbo.TableB SET val = 2 WHERE id = 1;
WAITFOR DELAY '00:00:10';
UPDATE dbo.TableA SET val = 2 WHERE id = 1;
COMMIT;

After about ten seconds one window fails with error 1205 and the other completes.

Step 2: Capture the deadlock graph

SQL Server’s built-in system_health Extended Events session already records every deadlock. Read the recent ones from its in-memory buffer:

;WITH x AS (
    SELECT CAST(xet.target_data AS xml) AS d
    FROM   sys.dm_xe_session_targets AS xet
    JOIN   sys.dm_xe_sessions        AS xe  ON xe.address = xet.event_session_address
    WHERE  xe.name = N'system_health' AND xet.target_name = N'ring_buffer'
)
SELECT ev.value('@timestamp', 'datetime2')        AS event_time_utc,
       ev.query('(data/value/deadlock)[1]')        AS deadlock_graph
FROM   x
CROSS APPLY d.nodes('RingBufferTarget/event[@name="xml_deadlock_report"]') AS t(ev)
ORDER BY event_time_utc DESC;

In SSMS, click the XML in the deadlock_graph column to open it. The ring buffer is limited in size, so old deadlocks eventually drop out. SQL Server also saves system_health events to .xel files in its log folder, which you can open in SSMS (File, Open, File) for a longer history.

If you want deadlock details in the SQL Server error log as well, turn on trace flag 1222 (undo it with DBCC TRACEOFF when finished, as it adds log noise):

DBCC TRACEON (1222, -1);

Step 3: Read the deadlock graph

The XML has three parts that matter:

Element What it tells you
victim-list Which process was killed
process-list (one process per session) For each: the login, the host, the application, and the exact SQL in inputbuf or executionStack that was running
resource-list (keylock, pagelock, objectlock…) The locked object and index, with owner-list (who holds it) and waiter-list (who wants it)

Follow the arrows: session 1 owns resource X and waits for Y; session 2 owns Y and waits for X. The two statements in the process list are the ones to investigate.

Look especially at the mode of each lock: X (exclusive, a writer), S (shared, a reader) and U (update). A reader in a deadlock is a strong hint that row versioning (below) would help.

Step 4: Fix it

Work down this list, from the cheapest fix to the most structural:

  1. Access objects in the same order everywhere. If every transaction updates Accounts before Orders, the cycle cannot form. This single rule prevents most deadlocks.
  2. Keep transactions short. Do the validation and the slow work first, then open the transaction, change data and commit immediately. Never wait for user input inside a transaction.
  3. Add or fix an index. Without a suitable index, an UPDATE ... WHERE scans and locks many rows, which multiplies collisions. A good index lets SQL Server lock only the rows it needs.
  4. Use row versioning for readers. With READ_COMMITTED_SNAPSHOT on, readers see the last committed version of a row instead of waiting for locks, so reader-writer deadlocks disappear:
    ALTER DATABASE SalesDB SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE;

    Test it first: it increases tempdb use and changes the read behaviour slightly. WITH ROLLBACK IMMEDIATE disconnects other sessions, so run it in a quiet moment.

  5. Take the lock you need up front. If a transaction reads a row and then updates it, reading with WITH (UPDLOCK) avoids two sessions both holding a shared lock and both wanting to upgrade:
    SELECT val FROM dbo.TableA WITH (UPDLOCK) WHERE id = 1;
  6. Retry in the application. Deadlocks cannot be eliminated entirely in a busy system. Catch error 1205 and re-run the transaction once or twice. SQL Server already rolled the victim back, so retrying is safe.

Retry pattern in T-SQL

DECLARE @tries int = 0;
WHILE @tries < 3
BEGIN
    BEGIN TRY
        BEGIN TRAN;
        -- your statements here
        COMMIT;
        BREAK;                       -- success: leave the loop
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0 ROLLBACK;
        IF ERROR_NUMBER() = 1205 AND @tries < 2
            SET @tries += 1;         -- deadlock victim: try again
        ELSE
            THROW;                   -- anything else, or last attempt: report it
    END CATCH
END

Quick diagnosis table

Symptom Likely cause First fix
Two sessions update the same two tables Opposite access order Standardise the order
A reader (S lock) is a deadlock participant Reads blocked by writers Row versioning
Many pagelock or objectlock entries Scans, missing index, lock escalation Add or fix the index
Deadlocks only at peak hours Long transactions under load Shorten transactions, retry logic

When you finish experimenting, drop the test tables: DROP TABLE dbo.TableA, dbo.TableB;

Did you find this helpful?Tap the heart to let us know. It takes one second and no account.

More tutorials like this

Leave a Comment

Your email address will not be published. Required fields are marked *

Bigland Network IT

Practical tutorials for people who run, build and fix things: operating systems, databases, development, networking and security.

Topics

More

Site

© 2026 Bigland Network. All rights reserved.Always test commands on a non-production system first.
Scroll to Top