// troubleshooting guide

Blocking and deadlocks

Sessions queue up or kill each other with deadlock errors. How to see the wait chain on SQL Server, PostgreSQL, MySQL and Oracle, read the deadlock graph, and fix the design that causes it.

Covers SQL Server PostgreSQL MySQL Oracle

The symptom

Queries hang for seconds or fail with deadlock errors. Locking is normal - the problems are blocking that lasts (a reader or writer stuck behind a transaction the app forgot to commit) and deadlocks (two sessions each holding what the other needs). Both are found the same way: by asking the engine who is waiting on whom.

Diagnose it

See the wait chain

SQL Server - who is blocked by whom, and what they are running:

SELECT r.session_id, r.blocking_session_id, r.wait_type, r.wait_time,
r.wait_resource, LEFT(t.text, 100) AS sql_text
FROM sys.dm_exec_requests AS r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t
WHERE r.blocking_session_id <> 0;

PostgreSQL - pg_blocking_pids builds the chain for you:

SELECT blocked.pid AS blocked_pid, LEFT(blocked.query, 60) AS blocked_query,
blocking.pid AS blocking_pid, LEFT(blocking.query, 60) AS blocking_query,
blocking.state AS blocking_state
FROM pg_stat_activity AS blocked
JOIN pg_stat_activity AS blocking
ON blocking.pid = ANY (pg_blocking_pids(blocked.pid));

The blocking session's query is whatever it ran last, which is often not the statement that took the lock: a session showing idle in transaction with a harmless SELECT is still holding the locks of an earlier UPDATE in the same transaction.

MySQL - the sys schema resolves InnoDB lock waits and even generates the kill statements. sql_kill_blocking_query only stops the blocker's current statement; if it is idle inside an open transaction, only sql_kill_blocking_connection releases the locks (by rolling the transaction back):

SELECT * FROM sys.innodb_lock_waits;

Oracle - the blocking session is a column:

SELECT sid, serial#, username, event, blocking_session, sql_id
FROM v$session
WHERE blocking_session IS NOT NULL;

In every engine the fix starts with the head of the chain - the session holding the lock - and the question is always the same: why does it hold the lock, and what is it waiting for? (An idle-in-transaction session on PostgreSQL, an uncommitted transaction someone's management tool left open, a long-running batch.)

Read the deadlock graph

A deadlock error means the engine chose a victim; the graph shows both queries and both locks. SQL Server keeps every deadlock in the system_health event session:

SELECT x.event_xml.value('(event/@timestamp)[1]', 'datetime2(3)') AS deadlock_time_utc,
x.event_xml.query('(event/data[@name="xml_report"]/value/deadlock)[1]') AS deadlock_graph
FROM sys.fn_xe_file_target_read_file(N'system_health*.xel', NULL, NULL, NULL) AS f
CROSS APPLY (SELECT CAST(f.event_data AS XML) AS event_xml) AS x
WHERE f.object_name = N'xml_deadlock_report'
ORDER BY deadlock_time_utc DESC;

This reads the session's event files, which hold far more history than its small in-memory ring buffer. The XML methods need SET QUOTED_IDENTIFIER ON (SSMS has it on; plain sqlcmd does not). Save a deadlock_graph value as an .xdl file and SSMS draws it.

On MySQL, SHOW ENGINE INNODB STATUS prints the latest deadlock under LATEST DETECTED DEADLOCK, and innodb_print_all_deadlocks = ON logs every one. On PostgreSQL, every deadlock is written to the server log as an ERROR naming both processes and their statements; turn on log_lock_waits (off by default) to also log any lock wait longer than deadlock_timeout, one second by default. Oracle raises ORA-00060 in the victim session and writes the deadlock graph to a trace file named in the alert log. The two statements in a graph usually arrive as one long line each - run them through the SQL-Formatter to see what each transaction touched, in which order.

Fix it

The graph's two statements tell you the pattern, and the fixes are nearly universal:

Shorten the transactions that hold locks. The head of the chain usually holds locks across work it should not: an application call, an HTTP request, or user think time inside a transaction. Commit as soon as the write is done - lock duration is the whole problem.

Index what the locks touch. On InnoDB, an UPDATE or DELETE (or SELECT ... FOR UPDATE) that finds its rows by scanning locks every row it reads, plus the gaps between them under the default REPEATABLE READ. On SQL Server a scanning writer takes update locks row by row and has to wait at every row another session holds. An index on the predicate shrinks that to the rows actually changed, and the contention often disappears with no other change. PostgreSQL only locks the rows it modifies, so this one matters less there.

Touch objects in the same order everywhere. Most deadlocks are two code paths updating tables A then B, and B then A. Pick one order and enforce it in both.

Let readers stop blocking writers where the engine allows it. PostgreSQL's MVCC means plain reads never block writes. Blocking there is writer against writer, or DDL: an ALTER TABLE needs an ACCESS EXCLUSIVE lock, waits behind any long-running SELECT on the table, and every new query on that table then queues behind the ALTER. Run migrations with SET lock_timeout = '5s' so they give up instead of stalling the application. On SQL Server, ALTER DATABASE [MyDb] SET READ_COMMITTED_SNAPSHOT ON (RCSI, the default in Azure SQL Database) gives readers the last committed version of each row from tempdb's version store instead of taking shared locks. On MySQL, InnoDB plain SELECTs are already non-locking consistent reads; only FOR UPDATE, FOR SHARE and the reads inside INSERT ... SELECT take locks.

Retry deadlocks, do not prevent them all. A deadlock victim should retry; the engine resolved an impossible wait. If a deadlock happens daily between the same statements, fix the pattern - if it happens weekly between different ones, retry logic is the correct design.

The checklist

Work through it in order. Each step gives you the evidence for the next one.

  1. Catch the blocking live: run the engine's wait-chain query above and find the head.
  2. Look at what the head-of-chain session is doing and whether it should still be in a transaction.
  3. For deadlocks, get the graph (system_health event file / SHOW ENGINE INNODB STATUS / server log / Oracle trace file) and identify both statements.
  4. Check both statements for missing indexes that make them lock more rows than they touch.
  5. Shorten the offending transactions: no external calls or waits inside them.
  6. Enforce one table access order across code paths that touch the same tables.
  7. Add retry-on-deadlock to the call sites that can safely retry.
  8. Re-run the wait-chain query at peak: the chain should be gone or trivially short.

Questions that come up

What is the difference between blocking and a deadlock?

Blocking is a queue: one session holds a lock, others wait, and they all get through once it commits. A deadlock is a cycle: two sessions each hold a lock the other needs, neither can proceed, and the engine kills one so the other can finish. Blocking is fixed by shortening or indexing; deadlocks additionally need consistent ordering and retry logic.

Why is an idle session blocking everyone?

Almost always a transaction someone left open: a management tool tab with an uncommitted edit, an application bug that opens a transaction and throws before committing (idle in transaction on PostgreSQL), or a long batch's open transaction between statements. The wait-chain query identifies the session; the fix is closing it and fixing the code that left it open.

Do indexes really fix lock contention?

When the contending statement reaches its rows by scan, yes: it takes locks on every row it reads past, not just the rows it matches. An index that turns the scan into a seek cuts the locked row count by orders of magnitude, which is why contention sometimes appears after data growth with no code change - see the bad index usage guide.

Should I use NOLOCK or READ UNCOMMITTED to stop blocking?

It trades correctness for latency: dirty reads can return rows that were never committed, and scans running during page splits can skip rows or read the same row twice. Read-committed-snapshot gives readers a consistent committed version instead, which is the change to make when reporting queries block on OLTP writes on SQL Server.

A deadlock happened once. Should I fix anything?

One deadlock between different statements a year is noise - add retry logic and move on. The graph is worth reading anyway: if both statements are hot application paths, the same cycle will repeat under load. SQL Server's system_health session, InnoDB status and the Postgres log all keep the evidence for you.

// fix it where the query lives

Run these queries in SQLly

SQLly is a native SQL workbench for macOS, Windows and Linux. The query plan viewer and formatter these guides link to are built into its editor.