Created
January 23, 2024 17:44
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;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