Problem Statement:
At times, we may need to understand the size of the tables in a database for various reasons. I often query these details to understand the growth of the data and clean up data for lower environments.
Code:
Here is a simple script to understand the rows, size of the table in a database.
You can further make changes to filter for any tables/group the results based on the indexes/partition etc.
SELECT sc.name + '.' + t.NAME AS TableName,
SUM(p.[Rows]) NumerOfRecords,
-- p.partition_number, i.index_id,i.name,
( SUM(a.total_pages) * 8 ) / 1024 AS TotalReservedSpaceMB,
( SUM(a.used_pages) * 8 ) / 1024 AS UsedDataSpaceMB,
( SUM(a.data_pages) * 8 ) / 1024 AS FreeUnusedSpaceMB
FROM sys.tables t
INNER JOIN sys.schemas sc ON sc.schema_id = t.schema_id
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.type_desc = 'USER_TABLE'
-- Replace with valid table name if you want to filter for a table
--AND t.NAME='YourTableName'
GROUP BY sc.name + '.' + t.NAME,
i.[object_id]
--,i.index_id, i.name, p.[Rows], p.partition_number
ORDER BY ( SUM(a.total_pages) * 8 ) / 1024 DESC