SQL Server Blocking Detection: Find Blocked Sessions
Blocking happens when one session holds a lock that another session needs, so the second session waits. The query below lists every request that is waiting on another session right now: who is blocked, who is blocking, the wait type and wait time, the database, and the SQL text on both sides.
Purpose and Overview
The finding that matters in a blocking incident is the head blocker, the one session at the front of the chain that is not itself waiting on anyone. Everything behind it is a symptom. sys.dm_exec_requests carries the blocking_session_id column that links each waiting request to the session it is waiting on, and joining it to sys.dm_exec_sessions and sys.dm_exec_sql_text turns that single column into a readable list of victims, owners and statements.
SQL Server produces no blocked process reports by default, so nothing tells you that a session has been stuck for ten minutes until a user complains. The server-wide blocked process threshold option changes that, but until someone sets it, this query is the quickest way to see the problem as it is happening. It reads the live state of the instance: a request that stopped waiting a second ago is already gone from the output.
The result has one row per blocked request, sorted by the longest wait first. Each row shows the blocked login, host and program, the blocking login, host and program, whether the blocker is sleeping or running, how many transactions the blocker has open, and the text of both batches. A blocker that shows Sleeping with an open transaction count above zero is the classic forgotten transaction: the client finished its last batch and never committed.
Code Breakdown
The query starts from sys.dm_exec_requests, which lists only requests that are currently executing, and adds session, connection and SQL text details for both ends of each block.
1SELECT
2 r.session_id AS blocked_session_id,
3 r.blocking_session_id AS blocking_session_id,
4 r.wait_type,
5 r.wait_resource,
6 r.wait_time / 1000.0 AS wait_seconds,
7 r.status,
8 s.login_name AS blocked_login,
9 s.host_name AS blocked_host,
10 s.program_name AS blocked_program,
11 DB_NAME(r.database_id) AS database_name,
12 SUBSTRING(
13 qt.text,
14 (r.statement_start_offset / 2) + 1,
15 (
16 CASE r.statement_end_offset
17 WHEN -1 THEN DATALENGTH(qt.text)
18 ELSE r.statement_end_offset
19 END - r.statement_start_offset
20 ) / 2 + 1
21 ) AS blocked_sql_text,
22 bs.login_name AS blocking_login,
23 bs.host_name AS blocking_host,
24 bs.program_name AS blocking_program,
25 bs.status AS blocking_session_status,
26 bs.open_transaction_count AS blocking_open_tran_count,
27 SUBSTRING(bqt.text, 1, 4000) AS blocking_sql_text
28FROM
29 sys.dm_exec_requests AS r
30 INNER JOIN sys.dm_exec_sessions AS s
31 ON r.session_id = s.session_id
32 LEFT JOIN sys.dm_exec_sessions AS bs
33 ON r.blocking_session_id = bs.session_id
34 LEFT JOIN sys.dm_exec_requests AS br
35 ON r.blocking_session_id = br.session_id
36 LEFT JOIN sys.dm_exec_connections AS bc
37 ON r.blocking_session_id = bc.session_id
38 OUTER APPLY sys.dm_exec_sql_text(r.sql_handle) AS qt
39 OUTER APPLY sys.dm_exec_sql_text(
40 ISNULL(br.sql_handle, bc.most_recent_sql_handle)) AS bqt
41WHERE
42 r.blocking_session_id > 0
43ORDER BY
44 r.wait_time DESC;
Filtering to Blocked Requests
WHERE r.blocking_session_id > 0 keeps only requests that are waiting on another session. A blocking_session_id of NULL or 0 means the request is not blocked, or that the blocker's session information is not available. The filter also drops the negative values on purpose:
-2means the blocking resource is owned by an orphaned distributed transaction.-3means it is owned by a deferred recovery transaction.-4means the owner of a blocking latch could not be determined because of internal latch state transitions.-5means the latch owner is not tracked for that latch type. By itself,-5is not a performance problem; it shows a session waiting on an asynchronous action, and it can be common on a busy server.
If you suspect an orphaned distributed transaction or a database stuck in deferred recovery, change the predicate to r.blocking_session_id < 0 and look at those rows separately.
Joining Sessions for Login and Host Details
sys.dm_exec_requests holds the wait and blocking columns but no login, host or program name. sys.dm_exec_sessions supplies them. The script joins it twice: s for the blocked session and bs for the blocking session. The host name is supplied by the client application and can be inaccurate, so treat it as a lead for who to call, not as proof.
The LEFT JOIN on bs matters. If the blocker's session row cannot be found, an inner join would silently remove the victim from the output, which is the opposite of what a monitoring query should do.
Getting the Blocker's SQL Text, Including an Idle Blocker
sys.dm_exec_sql_text is a table-valued function that takes a sql_handle and returns the batch text. For the blocked request the handle comes straight from r.sql_handle. The blocking side needs more care, because the blocker may have no active request at all. A session that ran a statement inside BEGIN TRAN and then went quiet still holds its locks, but sys.dm_exec_requests has no row for it.
For that case the script falls back to most_recent_sql_handle from sys.dm_exec_connections, the SQL handle of the last request executed on the connection. ISNULL(br.sql_handle, bc.most_recent_sql_handle) picks the running request's handle when one exists and the last batch the connection ran otherwise. Both applies use OUTER APPLY, so a row survives even when the handle is NULL or the text is NULL for an encrypted object.
For an idle blocker, the text returned is the last batch it ran, not necessarily the statement that took the lock. It is still usually enough to recognise the application code that opened the transaction.
Extracting the Exact Blocked Statement
The SUBSTRING on the blocked side uses statement_start_offset and statement_end_offset to cut the currently executing statement out of the batch. Both offsets are in bytes starting at 0, and the text is nvarchar, so each character takes two bytes: dividing by 2 converts to character positions. An end offset of -1 means the statement runs to the end of the batch, which is why the CASE substitutes DATALENGTH(qt.text). The blocking side is cut to the first 4,000 characters of the batch rather than to a single statement, because an idle blocker has no current statement offsets.
Wait Columns
wait_time is the duration of the current wait in milliseconds, so dividing by 1000.0 gives seconds. wait_type names the kind of wait, and wait_resource names the resource the request is waiting for, which is the quickest way to see whether the contention is on a row, a page, a key or a table. When a request is running in parallel, wait_type, wait_time and wait_resource are reported only for the coordinator thread, so for parallel queries confirm the details in sys.dm_os_waiting_tasks.
Key Benefits and Use Cases
- Diagnose an active slowdown. Run it when users report timeouts and you get the blocked requests, their waits and the owners of the blocking sessions in one result set.
- Find the head blocker. The head blocker is the session whose ID appears in the
blocking_session_idcolumn of other rows but does not appear asblocked_session_iditself. Sort or filter the result on that relationship to find the front of the chain. - See both sides of the block. Blocked and blocking SQL text sit on the same row, so you can tell whether a long reporting query or a forgotten transaction is the cause.
- Spot the sleeping blocker.
blocking_session_status = 'Sleeping'together with a non-zeroblocking_open_tran_countpoints at a client that left a transaction open. - Trace multi-session chains. When session A blocks B and B blocks C, both B and C appear as rows, and C's blocker is B, so the chain can be followed upward.
- Know who to call. Login, host and program name for both sessions identify the application team that owns the connection.
Performance Considerations
- The data is a snapshot. The views report the instance's current state. Blocking that cleared before you ran the query leaves no trace in these views, so this query cannot answer what happened last night.
- Cost is low, but not zero. The query reads only dynamic management views and runs quickly.
sys.dm_tran_locksis the exception: it can return a very large result on a busy production instance, so filter it before you join it. - Permissions decide what you see. With
VIEW SERVER STATEon the server you see all executing sessions; without it you see only your own session, and the query will look like there is no blocking. On SQL Server 2022 and later,sys.dm_exec_requestsrequiresVIEW SERVER PERFORMANCE STATEinstead. - Availability group secondaries. On a readable secondary configured as read-intent only, the connection must specify
applicationintent=readonlyor the access check onsys.dm_exec_requestsdoes not pass for the availability group databases, even withVIEW SERVER STATE. - Isolation level changes the picture. With the default READ COMMITTED behavior (the
READ_COMMITTED_SNAPSHOToption off), readers take shared locks and are blocked by writers, and block them in turn. With the option on, read operations under READ COMMITTED use row versioning and acquire only schema stability locks, so readers stop taking part in blocking. Check the setting withSELECT is_read_committed_snapshot_on FROM sys.databases WHERE name = DB_NAME(). - Repeated rows are possible. A session can have more than one request, and a session can have more than one connection row, so a block that involves such a session can show up on more than one line.
Practical Tips
- Capture it on a schedule. A SQL Agent job that runs the query every minute or so and inserts the result into a history table gives you evidence after the incident is over. Add a
GETDATE()column to the insert. - Turn on blocked process reports.
sp_configure 'blocked process threshold'sets the number of seconds a task must be blocked before a report is generated. Values range from 5 to 86,400. The lock monitor wakes every 5 seconds, so 5 is the shortest interval that can be detected. The setting is an advanced option, so runsp_configure 'show advanced options', 1andRECONFIGUREfirst, then set the value andRECONFIGUREagain. - Alert on the report. The
blocked_process_reportevent can be captured by an Extended Events session, and an alert can be defined to run when it fires, for example to page the on-call DBA. That is more dependable than a person running this query by hand during an outage. - Look at what the locks are. For the head blocker, query
sys.dm_tran_locksfiltered to itsrequest_session_id. Therequest_statuscolumn reportsGRANTEDorWAITamong its values, andresource_typenames the kind of resource, such asOBJECT,PAGE,KEYorRID. - Read the last statement.
DBCC INPUTBUFFER(<session_id>)returns the last statement a session submitted; to look at another session it needsVIEW SERVER STATEorsysadminmembership.sys.dm_exec_input_bufferreturns similar information in a result set that is easier to join and filter. - Find idle sessions with open work. Query
sys.dm_exec_sessionsfor rows whereopen_transaction_count > 0and no matching row exists insys.dm_exec_requests. - Kill only as a last resort.
KILL <session_id>ends the session and rolls back its open transactions, which can take a long time if the transaction did a lot of work.KILL <session_id> WITH STATUSONLYreports rollback progress without killing anything further. Confirm with the application owner before ending a production session.
Conclusion
This query shows the blocked requests, the sessions blocking them, the waits and the SQL on both sides, including the last batch of an idle blocker. Run it at the first report of slowness to find the head blocker, then use the lock and input buffer follow-ups to see why it is holding on. For recurring problems, pair it with a scheduled history capture and the blocked process threshold so the evidence exists before anyone asks for it.
References
- sys.dm_exec_requests (Transact-SQL) — columns, blocking_session_id values and permissions for active requests
- sys.dm_exec_sessions (Transact-SQL) — login, host, program, status and open transaction count per session
- sys.dm_exec_connections (Transact-SQL) — most_recent_sql_handle for the last request on a connection
- sys.dm_exec_sql_text (Transact-SQL) — table-valued function that returns batch text for a sql_handle
- sys.dm_tran_locks (Transact-SQL) — lock requests, their status and the resources they cover
- Server configuration: blocked process threshold — enabling blocked process reports and the 5 to 86,400 second range
- Understand and resolve SQL Server blocking problems — finding the head blocker and the common blocking scenarios
- KILL (Transact-SQL) — ending a session, rollback time and WITH STATUSONLY
- sys.databases (Transact-SQL) — is_read_committed_snapshot_on and other database settings
- ktaranov/sqlserver-kit on GitHub — repository of SQL Server scripts, tools and links for DBAs
Posts in this series
- SQL Server Table Row Count Report: Complete T-SQL Script
- Generate sp_spaceused Commands for All User Tables in T-SQL
- SQL Server Blocking Detection: Find Blocked Sessions
- SQL Server Database Size Report for All Databases
- SQL Server Long-Running Queries: Find Active Sessions
- SQL Server TempDB Usage and Contention Report
- SQL Server Database File Space Usage Report
- SQL Server Get Table and Index Storage Size Report Script
- Age Open Transactions with sys.dm_tran_active_transactions
- Decode PLE and Buffer Cache Hit Ratio via cntr_type Codes
- Spot Low-Memory Conditions with sys.dm_os_process_memory
- Track Azure SQL Database Load with sys.dm_db_resource_stats
- Inventory Open Cursors per Session with sys.dm_exec_cursors