DBA Scripts: Get Temp DB Hotspots

🔧Part of the DBA-Tools Project, copy/paste SQL Server scripts and health checks.In: Storage & Capacity

Temp DB is shared by every database and every session on the instance: temp tables, table variables, sort and hash spills, version store for snapshot isolation, all of it lands in the same handful of files. When Temp DB is under pressure, contention or growth events, the first question is always “who’s actually using it right now,” and that’s not obvious from a single system-wide view.

This script identifies exactly which sessions are consuming the most Temp DB space at the moment it’s run, with what they’re waiting on if anything, so the investigation starts from a specific session instead of a guess.


Why Temp DB Hotspots Matters

A single runaway session (a bad query building a huge worktable, a poorly-scoped batch process, a spill from an underestimated memory grant) can dominate Temp DB and slow down every other session sharing it:

  • Temp DB contention (PAGELATCH waits on allocation pages) affects every session using it, not just the one causing it
  • A session holding a large amount of Temp DB space is directly identifiable, rather than inferred from aggregate file growth
  • Distinguishing user objects (explicit temp tables/variables) from internal objects (spills, sort/hash work) narrows down whether the cause is application code or a query plan problem
  • The wait_type and elapsed_sec columns show whether the top consumer is actively running or just holding space from earlier work

When to Run This Script

  • Investigating Temp DB contention or unexpected growth
  • Routine SQL Server health checks on Temp DB-heavy workloads
  • Diagnosing a sudden slowdown affecting many sessions at once
  • Reviewing a server you’ve just inherited, to understand its Temp DB usage pattern

The Script

✓ Verified
  • Tested on: SQL Server 2025 (RTM CU8), Windows lab instance
  • Last verified: 2026-10-31 (re-run after a script fix; screenshot from 20 Jul)
  • Permissions: VIEW SERVER STATE
  • Safety: read-only, impact low
/*
Script Name : Get-TempdbHotspots
Category    : maintenance-and-reliability
Purpose     : Identify sessions consuming the most TempDB space for contention and spill triage.
Author      : Peter Whyte (https://sqldba.blog/dba-scripts-get-temp-db-hotspots/)
Requires    : VIEW SERVER STATE
Notes       : Sizes are TempDB space held now (allocated minus deallocated), running queries included.
              elapsed_sec is NULL when the session has no request running.
              Tested on SQL Server 2025.
*/
-- SAFE:ReadOnly
-- IMPACT:Low
SET NOCOUNT ON;
SET QUOTED_IDENTIFIER ON;

WITH running_tasks AS (
    SELECT
        tsu.session_id,
        SUM(tsu.user_objects_alloc_page_count - tsu.user_objects_dealloc_page_count) AS user_pages,
        SUM(tsu.internal_objects_alloc_page_count - tsu.internal_objects_dealloc_page_count) AS internal_pages
    FROM sys.dm_db_task_space_usage AS tsu
    GROUP BY tsu.session_id
),
held AS (
    SELECT
        ssu.session_id,
        ssu.user_objects_alloc_page_count - ssu.user_objects_dealloc_page_count
            + ISNULL(rt.user_pages, 0) AS user_pages,
        ssu.internal_objects_alloc_page_count - ssu.internal_objects_dealloc_page_count
            + ISNULL(rt.internal_pages, 0) AS internal_pages
    FROM sys.dm_db_session_space_usage AS ssu
    LEFT JOIN running_tasks AS rt ON rt.session_id = ssu.session_id
)
SELECT
    h.session_id,
    s.login_name,
    s.host_name,
    s.program_name,
    DB_NAME(r.database_id) AS active_database,
    CAST(h.user_pages * 8.0 / 1024 AS DECIMAL(10,2)) AS user_objects_mb,
    CAST(h.internal_pages * 8.0 / 1024 AS DECIMAL(10,2)) AS internal_objects_mb,
    CAST((h.user_pages + h.internal_pages) * 8.0 / 1024 AS DECIMAL(10,2)) AS total_tempdb_mb,
    r.wait_type,
    CAST(r.total_elapsed_time / 1000.0 AS DECIMAL(10,1)) AS elapsed_sec
FROM held AS h
JOIN sys.dm_exec_sessions AS s ON s.session_id = h.session_id
LEFT JOIN sys.dm_exec_requests AS r ON r.session_id = h.session_id
WHERE s.is_user_process = 1
  AND h.user_pages + h.internal_pages > 0
ORDER BY total_tempdb_mb DESC;

It returns every session holding Temp DB space right now, ranked by total, split into user objects versus internal objects. Sizes are space held now (allocated minus deallocated), and queries still running are included through sys.dm_db_task_space_usage.


How To Run From The Repo

Clone DBA Tools, initialize and run the script:

# Clone dba-tools repo:
git clone https://github.com/peterwhyte-lgtm/dba-tools

# Initialize environment:
cd dba-tools
.\Initialize-Environment.ps1

# Rank sessions by current Temp DB space held:
.
un.ps1 Get-TempdbHotspots

# To run against a remote sql server:
.
un.ps1 Get-TempdbHotspots -ServerInstance SQLSERVER01

This script lives in the repo at:


Example Output

Get-TempDbHotspots output showing key columns, SQL Server output

To get a real, non-empty result (usage is transient by nature, most sessions release it as soon as they finish), this was captured with a session actively holding a SELECT ... INTO #temp of about half a million rows:

session_id login_name program_name user_objects_mb internal_objects_mb total_tempdb_mb wait_type
60 PWSQL01\Peter Core .Net SqlClient Data Provider 71.44 0.00 71.44

Understanding the Results

  • user_objects_mb: space used by explicit temp tables and table variables created by application or ad-hoc code. High values here usually trace back to specific queries or procedures.
  • internal_objects_mb: space used by SQL Server itself for sort/hash spills, worktables, and similar internal work. High values here often mean a query’s memory grant was too small for what it actually needed.
  • total_tempdb_mb: the sort key. The session at the top is the one to investigate first.
  • wait_type: blank/NULL means the session isn’t actively running a request right now (it may be holding space from a completed statement in an open transaction). A wait type present means it’s actively running and worth checking what it’s waiting on.

An empty result set is normal and expected between busy periods; usage is transient, most sessions release it as soon as they finish.


Best Practices

  • When investigating contention, run this repeatedly (or capture a snapshot during the actual slow period) since usage is transient and can be gone by the time you look.
  • A consistently high internal_objects_mb on the same query points at a memory grant sizing problem, worth investigating with the query’s actual execution plan.
  • Pair this with Temp DB file configuration checks; even a legitimate workload can suffer if it isn’t sized or striped appropriately for the load it carries.

MS Docs: sys.dm_db_session_space_usage · sys.dm_exec_sessions · sys.dm_exec_requests


Related Scripts

You may also find these scripts useful:


Frequently Asked Questions

Why did the script return nothing when I ran it?

Most likely because nothing was using significant Temp DB space at that exact moment; usage is transient. Run it again during the actual period of contention or slowness, or while the suspect workload is running.

Is internal object usage always a problem?

No. Every complex query that sorts, hashes, or spills uses Temp DB internally as a normal part of execution. It’s only worth investigating when it’s unusually high, sustained, or tied to a specific query causing contention for others.


Summary

Temp DB contention affects everyone sharing the instance, which makes finding the actual source fast a real priority, not just a nice-to-have. Knowing exactly which session is holding the space turns a vague “it’s slow” into a specific, actionable investigation.

Run this script while a suspected issue is actively happening, since usage is transient and the picture changes quickly.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *