To get the size of a specific table in T-SQL, the fastest method is using the built-in system stored procedure sp_spaceused. By executing EXEC sp_spaceused 'TableName', SQL Server returns the number of rows, reserved space, data space, index size, and unused space for that table. This is essential for database administrators and developers to identify "bloated" tables, plan disk capacity, and optimize index maintenance.
What You'll Need
- SQL Server Management Studio (SSMS) or Azure Data Studio.
- A connection to the target SQL Server instance.
- View Definition or View Database State permissions (or membership in the db_datareader role) to access system metadata.
Step-by-Step
- Open a New Query Window: Launch SSMS, connect to your server, right-click on your database in the Object Explorer, and select New Query.
- Use the Basic Procedure: For a quick check of a single table, type and execute the following command:
ReplaceEXEC sp_spaceused 'YourTableName';'YourTableName'with the actual name of your table. If the table is in a specific schema (likesales.Orders), include the schema name. - Analyze the Results: The output will provide five key columns:
- rows: The total number of records in the table.
- reserved: Total space allocated for the table (includes data, indexes, and unused space).
- data: The actual space used by the row data.
- index_size: The space used by all indexes associated with the table.
- unused: Space that has been reserved but is not yet containing data.
- Get Sizes for All Tables (Advanced): If you need a report for every table in the database,
sp_spaceusedcannot be called directly in aSELECTstatement. You must use a temporary table to capture the results. Execute this script:CREATE TABLE #TableSize ( name NVARCHAR(128), rows CHAR(11), reserved VARCHAR(18), data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18) ); EXEC sp_MSforeachtable 'INSERT INTO #TableSize EXEC sp_spaceused ''?'''; SELECT * FROM #TableSize ORDER BY CAST(REPLACE(reserved, ' KB', '') AS INT) DESC; DROP TABLE #TableSize; - Use System Views for Precise Control: For more granular control or to avoid the overhead of
sp_MSforeachtable, querysys.allocation_unitsandsys.partitions:SELECT t.name AS TableName, s.name AS SchemaName, p.rows AS RowCounts, SUM(a.total_pages) * 8 AS TotalSpaceKB, SUM(a.used_pages) * 8 AS UsedSpaceKB, (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB 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 GROUP BY t.name, s.name, p.rows ORDER BY TotalSpaceKB DESC;
Common Mistakes
- Confusing Reserved vs. Used Space: A common error is looking only at "used" space. "Reserved" space is what the OS actually allocates to the database file; if reserved space is significantly higher than used space, you may have internal fragmentation.
- Ignoring Schemas: If your table is not in the default
dboschema, simply callingsp_spaceused 'TableName'may result in an "Object not found" error. Always use'SchemaName.TableName'. - Running Heavy Queries on Production: While
sp_spaceusedis lightweight, running a loop across thousands of tables usingsp_MSforeachtablecan cause temporary locks or resource spikes on extremely large production databases. - Misinterpreting KB: Remember that SQL Server reports these values in Kilobytes (KB). To get Megabytes (MB), divide the result by 1,024.
Tips
- Check Index Bloat: If the
index_sizeis significantly larger than thedatasize, consider reviewing your indexing strategy. You may have redundant or overlapping indexes. - Update Statistics: The row count returned by
sp_spaceusedis based on metadata. If your statistics are outdated, the row count might be slightly inaccurate. RunUPDATE STATISTICS TableNamefor the most current count. - Use Format Functions: When writing custom scripts, use
FORMAT()orCAST()to convert the KB values into MB or GB for better readability in reports.
Troubleshooting
If the query does not return the expected results, try these steps in order:
- Verify Permissions: Ensure your user account has the necessary permissions to view system catalogs. If you see an "Access Denied" error, ask your DBA for
VIEW DEFINITIONpermissions. - Check Table Name Spelling: Ensure there are no typos and that you are connected to the correct database. Use the dropdown menu in the SSMS toolbar to verify the active database.
- Address "Object Not Found": If the table exists but isn't found, explicitly add the schema (e.g.,
EXEC sp_spaceused 'Sales.Customers'). - Handle Temporary Tables: Note that
sp_spaceusedworks differently for local temporary tables (#Table). You must execute the procedure within thetempdbdatabase context.
Frequently Asked Questions
Why is my table size larger than the sum of its data?
This is usually due to "Reserved" space. SQL Server allocates space in extents (groups of 8 pages). If a table needs a small amount of extra space, SQL Server reserves a full extent, leading to a gap between the actual data size and the reserved size.
Does sp_spaceused include the size of LOB data?
Yes, sp_spaceused includes data stored in Large Object (LOB) columns, such as VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX), as these are tracked in the allocation units.
Can I get the size of a specific index instead of the whole table?
No, sp_spaceused provides the aggregate size of all indexes. To find the size of a specific index, you must query sys.allocation_units and join it with sys.indexes using the index_id.
How often should I check table sizes?
This depends on your data growth rate. For most environments, a weekly or monthly check is sufficient to monitor growth trends and identify tables that require archiving or partitioning.
Is there a GUI way to do this without T-SQL?
Yes. In SSMS, right-click the database, go to Reports > Standard Reports > Disk Usage by Top Tables. This provides a visual breakdown of the largest tables in your database.