Created
December 19, 2024 13:36
-
-
Save petesql/855a212c98dfc92b8fc9ba595a821ba6 to your computer and use it in GitHub Desktop.
Get Index Fragmentation Levels SQL Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Script to retrieve index fragmentation levels in SQL Server | |
-- This script will list fragmented indexes in the database, showing table name, index name, fragmentation percentage, and more | |
SELECT | |
OBJECT_NAME(s.OBJECT_ID) AS TableName, -- Table name where the index is located | |
i.name AS IndexName, -- Name of the index | |
ROUND(s.avg_fragmentation_in_percent, 2) AS FragmentationPercentage, -- Fragmentation percentage rounded to 2 decimal places | |
s.page_count AS PageCount, -- Number of pages used by the index | |
i.type_desc AS IndexType, -- Type of the index (Clustered, Nonclustered, etc.) | |
s.stats_id AS StatsID -- Statistics ID for the index | |
FROM | |
sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, 'DETAILED') AS s | |
JOIN | |
sys.indexes AS i | |
ON | |
s.OBJECT_ID = i.OBJECT_ID AND s.index_id = i.index_id | |
WHERE | |
i.type_desc IN ('CLUSTERED', 'NONCLUSTERED') | |
ORDER BY | |
s.avg_fragmentation_in_percent DESC; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment