Earlier I had written a blog post SQL SERVER – List Tables with Size and Row Counts. Jason Horner, an SQL Server Expert, left a comment to the blog post and improved my earlier query. Thanks, Jason for fixing the rounding bug in the script for integer division.
SELECT t.NAME AS TableName, SUM(p.rows) AS RowCounts, (SUM(a.total_pages) * 8) / 1024.0 as TotalSpaceMB, (SUM(a.used_pages) * 8) / 1024.0 as UsedSpaceMB, (SUM(a.data_pages) * 8) /1024.0 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 i.OBJECT_ID > 255 AND i.index_id IN (0,1) GROUP BY t.NAME ORDER BY TotalSpaceMB DESC
I hope you find this short but effective script to find Size and Row Counts helpful. Here are few other blog posts which you may find interesting. If you have any other questions, do let me know by leaving a comment on the blog post. As you can see I read everything and do my best to reply.
If you liked this blog, please do not forget to subscribe to my YouTube Channel – SQL in Sixty Seconds.
Here are my few recent videos and I would like to know what is your feedback about them.
- MAX Columns Ever Existed in Table – SQL in Sixty Seconds #182
- Tuning Query Cost 100% – SQL in Sixty Seconds #181
- Queries Using Specific Index – SQL in Sixty Seconds #180
- Read Only Tables – Is it Possible? – SQL in Sixty Seconds #179
- One Scan for 3 Count Sum – SQL in Sixty Seconds #178
- SUM(1) vs COUNT(1) Performance Battle – SQL in Sixty Seconds #177
- COUNT(*) and COUNT(1): Performance Battle – SQL in Sixty Seconds #176
Reference: Pinal Dave (http://blog.SQLAuthority.com)
3 Comments. Leave new
Good one. Few changes, so that the result matches to sp_spaceused which is being used from many years.
SELECT t.NAME AS TableName, SUM(p.rows) AS RowCounts,
(SUM(a.total_pages) * 8) / 1024.0 as ReservedSizeMB,
(SUM(a.data_pages) * 8) /1024.0 as DataSizeMB,
((SUM(a.used_pages) * 8)-(SUM(a.data_pages) * 8)) / 1024.0 as IndexSizeMB,
((SUM(a.total_pages) * 8)-(SUM(a.used_pages) * 8)) / 1024.0 as UnUsedSizeMB
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 i.OBJECT_ID > 255 AND i.index_id IN (0,1)
GROUP BY t.NAME
ORDER BY ReservedSizeMB DESC
go
Great to see this script.
Hi, good script, but doesn’t this ignore the space occupied by additional indexes?
If so, wouldn’t it mean that projecting growth on a table from a time series of this data underestimates that space required?
(admitttedly, only significant if the tables are very large & the indexes copious, but could be relevant if your db is very big)