
Explanation of Find Fragmented Indexes in a Database in SQL Server
When data is frequently inserted, updated, or deleted, indexes can become fragmented. Fragmentation leads to slower query performance because SQL Server has to work harder to read data from scattered pages.
You can run a script to identify which indexes are fragmented and how much. This helps decide whether to reorganize or rebuild them.
Example Script:
- SELECT
- OBJECT_SCHEMA_NAME(ips.object_id) AS SchemaName,
- OBJECT_NAME(ips.object_id) AS TableName,
- i.name AS IndexName,
- ips.index_id,
- ROUND(ips.avg_fragmentation_in_percent, 2) AS FragmentationPercent,
- ips.page_count
- FROM
- sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, 'LIMITED') AS ips
- JOIN
- sys.indexes AS i ON ips.object_id = i.object_id AND ips.index_id = i.index_id
- WHERE
- i.index_id > 0 -- exclude heaps
- AND ips.page_count > 100 -- ignore small indexes
- ORDER BY
- FragmentationPercent DESC;
Conclusion:
This script lists all fragmented indexes in your database with their fragmentation level. Use it to monitor index health and decide which indexes to reorganize (if 5–30% fragmented) or rebuild (if over 30%). Regular monitoring improves database performance and keeps queries running efficiently.
Post Comment
Your email address will not be published. Required fields are marked *