Get Table and Index storage size in SQL Server
To quickly spot table and index storage sizes in SQL Server, we use a stored procedure called sp_spaceused
. For each table, execute it individually and it will fetch detailed stats on space usage:
Now, if you want to automate this for all tables, we insert the results into a temporary table. We'll use a stored procedure named sp_MSforeachtable
to gather stats for all tables in a single run:
This script collects size data for all tables and indexes, shows the compilation, and cleans up afterwards.
Delve deeper with dynamic management views
For a finer understanding of storage usage, we can use SQL Server's dynamic management views (DMVs). They provide insights into data distribution, index usage, and storage efficiency.
Using dynamic management views to gather space usage
This query reveals the used storage by heaps and clustered indexes.
Special note for Non-clustered indexes
Non-clustered indexes, which also consume space, require separate computation:
Understanding the space used by non-clustered indexes assists in performance tuning and storage management.
Essential considerations when measuring space
-
Unused space: Factor in space allocated but not currently in use. Extract this from dynamic management view
sys.dm_db_partition_stats
. -
Internal objects: Be mindful of internal tables that SQL Server uses. These include those used for XML storage or spatial indexes.
-
Table partitioning: If your tables are partitioned, your query will need an upgrade to accurately total the sizes across partitions.
-
Database snapshots: Working with snapshots? Remember, size computations only reflect the changes made since the snapshot was taken.
Was this article helpful?