When you add or maintain an index, you often want a quick health check:
- how fragmented is it,
- how big is it,
- what fill factor was applied,
- and is it even enabled?
Here is a query that pulls all of that for one specific index.
The Information Query
| |
Now, you need to understand some important rules:
sys.dm_db_index_physical_statsis a function, not a table. You call it withCROSS APPLY(orOUTER APPLY) so it runs once per index row; a plainJOINwon’t work. Running it requires at leastCONTROLpermission on the table.LIMITEDoption is the cheapest mode to query the information. It only scans the parent (non-leaf) pages of the B-tree, which makes it fast but selective: you getavg_fragmentation_in_percentandpage_count, but detail columns such asavg_page_space_used_in_percent,fragment_count, andrecord_countcome backNULL. Switch toSAMPLEDorDETAILEDwhen you need those.NULLis a wildcard, and typos are silent.DB_ID()andOBJECT_ID()returnNULLwhen a name can’t be resolved, and the function readsNULLas “all databases / all objects.” A misspelled table name won’t raise an error—it’ll happily scan everything.
An Example
So, let’s suppose you have a table and an index you just created:
| |
Running the health-check query against it returns a single row: the index name, NONCLUSTERED, its current fragmentation, its size in MB, and whether it’s disabled (0).
Documentation
The official Microsoft documentation is:
sys.dm_db_index_physical_stats (Transact-SQL)—https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-index-physical-stats-transact-sql
You may also want the catalog views the query joins:
sys.indexes (Transact-SQL)—https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-indexes-transact-sqlsys.partitions (Transact-SQL)—https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-partitions-transact-sql
It applies to SQL Server, Azure SQL Database, Azure SQL Managed Instance, Azure Synapse Analytics, and Analytics Platform System (PDW).
If you want a specific product version, append the view parameter to the URL (e.g., ?view=sql-server-ver17 for the latest, or `?view=sql-server-ver16’).
Follow me
Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.
Photo by Microsoft Server
