How to Check Index Fragmentation on Indexes in a Database
Issue
SQL Queries taking longer than normal to complete.Cause
when a database is frequently updated via INSERT, UPDATE, or DELETE statements, over time these modifications can cause the information in the index to become scattered in the database (fragmented). Fragmentation exists when indexes have pages in which the logical ordering, based on the key value, does not match the physical ordering inside the data file.
when a database is frequently updated via INSERT, UPDATE, or DELETE statements, over time these modifications can cause the information in the index to become scattered in the database (fragmented). Fragmentation exists when indexes have pages in which the logical ordering, based on the key value, does not match the physical ordering inside the data file.
If database indexes are fragmented, the SQL Server query optimizer may choose a non-optimal execution plan when using an index to resolve a query. Heavily fragmented indexes can degrade query performance and cause your application to respond slowly.
Resolution
*Warning: Irreparable database damage can occur. This procedure should only be performed by users familiar with SQL Server Management Studio. Databases should be backed up prior to performing this procedure.*
The following is a simple query that will list every index on every table in your database, ordered by the percentage of index fragmentation.
SELECT
dbschemas.[
name
]
as
'Schema'
,
dbtables.[
name
]
as
'Table'
,
dbindexes.[
name
]
as
'Index'
,
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM
sys.dm_db_index_physical_stats (DB_ID(),
NULL
,
NULL
,
NULL
,
NULL
)
AS
indexstats
INNER
JOIN
sys.tables dbtables
on
dbtables.[object_id] = indexstats.[object_id]
INNER
JOIN
sys.schemas dbschemas
on
dbtables.[schema_id] = dbschemas.[schema_id]
INNER
JOIN
sys.indexes
AS
dbindexes
ON
dbindexes.[object_id] = indexstats.[object_id]
AND
indexstats.index_id = dbindexes.index_id
WHERE
indexstats.database_id = DB_ID()
ORDER
BY
indexstats.avg_fragmentation_in_percent
desc
This query can be modified to focus on specific tables by appending the table name to the 'WHERE' clause:
WHERE indexstats.database_id = DB_ID() and dbtables.[name] like '%%'
Depending on the index fragmentation percentage, fragmentation can be reduced by reorganizing or rebuilding. For heavily fragmented indexes (greater than 30%) a rebuilding process is needed, else index reorganizing is sufficient.
Comments
Post a Comment