Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Created January 23, 2024 17:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davepcallan/ee5240f30330caf58c76a2eececb83d5 to your computer and use it in GitHub Desktop.
Save davepcallan/ee5240f30330caf58c76a2eececb83d5 to your computer and use it in GitHub Desktop.
SQL Server query to get row counts and size (MB) for all tables in a DB
;WITH TableSizes AS (
SELECT
s.Name AS SchemaName,
t.NAME AS TableName,
p.rows AS RowCounts,
CAST(SUM(a.total_pages) * 8 / 1024.0 AS DECIMAL(10, 2)) AS TotalSpaceMB
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
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.TYPE = 'U'
GROUP BY
t.Name, s.Name, p.Rows
)
SELECT *
FROM TableSizes
ORDER BY
SchemaName ASC, RowCounts DESC, TableName ASC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment