Find recent deadlocks in SQL Server
SQL Server records every deadlock into system_health automatically. Here is how to read them back out.
The task
SQL Server runs an Extended Events session called system_health by default, and it records an xml_deadlock_report for every deadlock, so you can investigate one after the fact without having set up a trace. Each report lists the processes involved with their session ids and input buffers, the locked resources, and which process was chosen as the victim and rolled back.
The snippet
Written for SQL Server. Versions for PostgreSQL are under Variations.
WITH f AS (
SELECT CAST(event_data AS XML) AS x
FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL)
WHERE object_name = 'xml_deadlock_report'
)
SELECT f.x.value('(event/@timestamp)[1]', 'DATETIME2') AS deadlock_time_utc,
dl.d.value('count(process-list/process)', 'INT') AS processes,
dl.d.value('(process-list/process[@id = ../../victim-list/victimProcess[1]/@id]/@spid)[1]', 'INT') AS victim_spid,
dl.d.value('(process-list/process[@id = ../../victim-list/victimProcess[1]/@id]/inputbuf)[1]', 'NVARCHAR(2000)') AS victim_input,
dl.d.value('(resource-list/*/@objectname)[1]', 'NVARCHAR(256)') AS first_locked_object
FROM f
CROSS APPLY f.x.nodes('event/data[@name="xml_report"]/value/deadlock') AS dl(d)
ORDER BY deadlock_time_utc DESC;
Cómo funciona
system_health writes to two targets: a ring buffer in memory and rolling system_health*.xel files in the instance's log directory. The query reads the files with sys.fn_xe_file_target_read_file, which resolves the relative name against that directory, keeps history across restarts and returns one row per event, so the WHERE on object_name skips everything that is not a deadlock. The ring buffer is the less reliable source: it is emptied on restart and holds a limited number of recent events of every kind, so a burst of other events pushes deadlocks out. On the instance used to test this page it held 770 copies of one memory warning and not the deadlock raised seconds earlier, which the files had. nodes() steps into each report's deadlock element. The victim is found by matching each process's id attribute against victim-list/victimProcess, and inputbuf is the last batch that process sent, which is often the statement that deadlocked. The timestamp is in UTC. To see both sides, run the variant and open the report XML; SQL Server Management Studio draws it as a graph if you save it with an .xdl extension. Reading these views needs VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE on SQL Server 2022 and later).
Variations
Dump the full deadlock report XML
SELECT x.value('(event/@timestamp)[1]', 'DATETIME2') AS deadlock_time_utc,
x.query('event/data[@name="xml_report"]/value/deadlock') AS report
FROM (
SELECT CAST(event_data AS XML) AS x
FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL)
WHERE object_name = 'xml_deadlock_report'
) f
ORDER BY deadlock_time_utc DESC;
PostgreSQL: deadlock counter per database
PostgreSQLSELECT datname, deadlocks
FROM pg_stat_database
WHERE deadlocks > 0
ORDER BY deadlocks DESC;
Questions that come up
Where does PostgreSQL record deadlocks?
In the server log. The victim's session logs ERROR: deadlock detected, with a DETAIL section naming each process, the lock it waited for and its statement. pg_stat_database.deadlocks counts them per database, so a rise in that counter tells you when to look in the log. log_lock_waits = on is a separate setting: it logs any lock wait longer than deadlock_timeout (1 second by default), which catches the near misses too.
How do I prevent a recurring deadlock?
Read the statements from the report and make every code path touch the same rows and tables in the same order, for example by sorting batch updates by key or by locking the parent row first (UPDLOCK in SQL Server, SELECT ... FOR UPDATE in PostgreSQL). A missing index is another common cause, because a scan locks many more rows than the statement changes. Shorter transactions make deadlocks rarer but do not fix an ordering conflict.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.