Quick Bit

Space used by table

Sometimes we just need a simple list of space used for some tables

Cl

Claus Munch

Jan 12, 2026 · 1 min read

10 views
Space used by table

Sometimes we just need a simple list of the space used by a (or a list of) table(s), that we can work with.
This simple stub, gives just that. Can be used as is or for further use in scripts. Nice and easy.


SELECT 
    t.name AS [Table Name],
    s.name AS [Schema],
    SUM(p.rows) AS [Row Count],    
    -- Total Reserved (Data + Index + Unused)
    CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS [Total Space MB],    
    -- Data Space (Heap or Clustered Index - index_id 0 or 1)
    CAST(ROUND(((SUM(CASE WHEN i.index_id < 2 THEN a.used_pages ELSE 0 END) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS [Data Space MB],    
    -- Index Space (Non-Clustered Indexes - index_id > 1)
    CAST(ROUND(((SUM(CASE WHEN i.index_id > 1 THEN a.used_pages ELSE 0 END) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS [Index Space MB],
    -- Unused Space (Reserved but not yet filled)
    CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS [Unused Space MB]
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON 
    -- Improved Join: Handles both In-Row data (linked by hobt_id) and LOB data (linked by partition_id)
    (a.type IN (1, 3) AND a.container_id = p.hobt_id) 
    OR 
    (a.type = 2 AND a.container_id = p.partition_id)
LEFT OUTER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
WHERE 
    t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
    -- ▼ EDIT AND/OR UNCOMMENT THE STRINGS BELOW ▼
    AND t.name LIKE '%post%'                                        -- PARTIAL NAME MATCH
    -- AND t.name IN ('YourTable1', 'YourTable2', 'YourTable3')     -- PROVIDE A LIST OF TABLES
    -- AND s.name = 'Transactions'                                  -- ONLY LOOK FOR TABLES IN SPECIFIC SCHEMA
    -- ▲ EDIT AND/OR UNCOMMENT THE STRINGS ABOVE ▲
GROUP BY 
    t.name, s.name
ORDER BY 
    [Total Space MB] DESC;
Share this article:

Related Articles