Skip to content
SeriouslySQL
Go back
SQL Shorts

Who's there?

If your server is sluggish, a job is taking longer than expected, or someone just says “the database is slow”, the first thing I want to know is who’s connected and what they’re running.

This script shows current active sessions: who’s logged in, the application they’re using, the statement and batch, how long it’s been running, and whether they’re being blocked.

SELECT
    s.session_id,
    s.login_name,
    s.host_name,
    s.program_name,
    s.status,
    r.start_time,
    DATEDIFF(SECOND, r.start_time, GETDATE()) AS duration_seconds,
    r.cpu_time,
    r.reads,
    r.writes,
    r.blocking_session_id,
    SUBSTRING(
        t.text,
        (r.statement_start_offset / 2) + 1,
        ((CASE r.statement_end_offset
            WHEN -1 THEN DATALENGTH(t.text)
            ELSE r.statement_end_offset
          END - r.statement_start_offset) / 2) + 1
    ) AS current_statement,
    t.text AS full_batch,
    r.plan_handle
FROM sys.dm_exec_sessions s
INNER JOIN sys.dm_exec_requests r
    ON s.session_id = r.session_id
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE s.is_user_process = 1
ORDER BY r.start_time ASC
ColumnWhat it tells you
blocking_session_idThe ID of the session blocking this one
duration_secondsHow long the current execution has been running
current_statementThe specific statement being executed right now
full_batchThe whole batch
plan_handlePass to sys.dm_exec_query_plan() to pull the actual execution plan

To include idle sessions with open transactions, update the WHERE clause:

WHERE s.is_user_process = 1
  AND (r.session_id IS NOT NULL OR s.open_transaction_count > 0)

If you want more detail without writing the query yourself, Adam Machanic’s sp_whoisactive does all of this and more. It’s a free stored procedure you install once and call with a single line. It surfaces wait types, tempdb usage, query plans and blocking chains in one result set, and it’s worth having on any server you support.


Share this post:

Previous Post
25 Years as a DBA
Next Post
Concerned about available disk space?