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:

  • -2 means the blocking resource is owned by an orphaned distributed transaction.
  • -3 means it is owned by a deferred recovery transaction.
  • -4 means the owner of a blocking latch could not be determined because of internal latch state transitions.
  • -5 means the latch owner is not tracked for that latch type. By itself, -5 is 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_id column of other rows but does not appear as blocked_session_id itself. 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-zero blocking_open_tran_count points 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_locks is 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 STATE on 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_requests requires VIEW SERVER PERFORMANCE STATE instead.
  • Availability group secondaries. On a readable secondary configured as read-intent only, the connection must specify applicationintent=readonly or the access check on sys.dm_exec_requests does not pass for the availability group databases, even with VIEW SERVER STATE.
  • Isolation level changes the picture. With the default READ COMMITTED behavior (the READ_COMMITTED_SNAPSHOT option 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 with SELECT 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 run sp_configure 'show advanced options', 1 and RECONFIGURE first, then set the value and RECONFIGURE again.
  • Alert on the report. The blocked_process_report event 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_locks filtered to its request_session_id. The request_status column reports GRANTED or WAIT among its values, and resource_type names the kind of resource, such as OBJECT, PAGE, KEY or RID.
  • Read the last statement. DBCC INPUTBUFFER(<session_id>) returns the last statement a session submitted; to look at another session it needs VIEW SERVER STATE or sysadmin membership. sys.dm_exec_input_buffer returns similar information in a result set that is easier to join and filter.
  • Find idle sessions with open work. Query sys.dm_exec_sessions for rows where open_transaction_count > 0 and no matching row exists in sys.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 STATUSONLY reports 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

Posts in this series