Skip to content

Instantly share code, notes, and snippets.

@pferreirafabricio
Last active January 24, 2024 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pferreirafabricio/4c07cba8b9f949df9be8f2d8862e15e7 to your computer and use it in GitHub Desktop.
Save pferreirafabricio/4c07cba8b9f949df9be8f2d8862e15e7 to your computer and use it in GitHub Desktop.
πŸ“Š Get row count and size for all tables in SQL Server
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
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