gpt-4o-mini-2024-07-18· openai
from WildChat-4.8M
mssql query to get below table information: rows reserved data index_size unused
- User
mssql query to get below table information: rows reserved data index_size unused
- Assistant
To get the information related to reserved space, data size, index size, and unused space for tables in a SQL Server (MSSQL) database, you can use the built-in system stored procedure
sp_spaceused. However, to get a more comprehensive result for all tables in a database, you can use the following query, which utilizes system views.Here's a sample query you might use to retrieve this information for all user tables:
sqlSELECT t.NAME AS TableName, s.name AS SchemaName, p.[rows] AS Rows, SUM(a.total_pages) * 8 AS ReservedKB, SUM(a.used_pages) * 8 AS UsedKB, (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedKB, SUM(a.used_pages) * 8 - SUM(a.data_pages) * 8 AS IndexSizeKB, SUM(a.data_pages) * 8 AS DataSizeKB FROM sys.tables AS t INNER JOIN sys.schemas AS s ON t.schema_id = s.schema_id INNER JOIN sys.indexes AS i ON t.object_id = i.object_id INNER JOIN sys.partitions AS p ON i.object_id = p.object_id AND i.index_id = p.index_id INNER JOIN sys.allocation_units AS a ON p.partition_id = a.container_id WHERE i.type <= 1 -- 0 = Heap, 1 = Clustered GROUP BY t.NAME, s.name, p.[rows] ORDER BY TableName;Explanation:
- sys.tables: Contains a row for each user-defined table.
- sys.schemas: Contains a row for each schema in the database.
- sys.indexes: Contains a row for each index and table in the database.
- sys.partitions: Contains a row for each partition of a table or index.
- sys.allocation_units: Contains a row for each allocation unit in the database.
Calculated Columns:
- ReservedKB: Total space reserved for the table (in KB).
- UsedKB: Space actually used by the table data (in KB).
- UnusedKB: Space reserved but not yet used (in KB).
- : Size of the indexes on the table (in KB).