Skip to content

Which Tables Are Taking Up How Much Space

Published: at 06:49 AM

This article explores a powerful T-SQL query that helps you identify tables and indexes that are consuming the most storage space in your database.

Tables and indexes, while essential for data organization and retrieval, can accumulate significant storage over time. Identifying space-consuming objects allows you to:

The Space Utilization Query:

The provided T-SQL query leverages several system views to gather detailed information about tables, indexes, and their storage footprint:

SELECT
  t.NAME AS TableName,
  i.name AS indexName,
  SUM(p.rows) AS RowCounts,
  SUM(a.total_pages) AS TotalPages,
  SUM(a.used_pages) AS UsedPages,
  SUM(a.data_pages) AS DataPages,
  (SUM(a.total_pages) * 8) / 1024 AS TotalSpaceMB,
  (SUM(a.used_pages) * 8) / 1024 AS UsedSpaceMB,
  (SUM(a.data_pages) * 8) / 1024 AS DataSpaceMB
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 p.partition_id = a.container_id
WHERE
  t.NAME NOT LIKE 'dt%' AND
  i.OBJECT_ID > 255 AND
  i.index_id <= 1
GROUP BY
  t.NAME, i.object_id, i.index_id, i.name
ORDER BY
  OBJECT_NAME(i.object_id);

Breakdown of the Query:

Using the Results:


Previous Post
Execute .csx as a Task in VSCode
Next Post
Readability Notes