Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / SQL
Tip/Trick

Find and Fix Fragmented Indexes

Rate me:
Please Sign up or sign in to vote.
4.93/5 (5 votes)
5 Feb 2014CPOL 11.4K   11   2
Quick tip to allow you to identify indexes that could do with defragmentation

Introduction

Over time, SQL server indexes become fragmented as data are inserted and deleted from the tables they refer to. Identifying these and defragmenting them can improve your database performance.

Using the Code

Replace [databasename] with your database name and then run the following SQL:

SQL
select object_name(a.object_id), b.name , a.avg_fragmentation_in_percent,  
'ALTER INDEX ' + B.NAME + ' ON ' + OBJECT_NAME(a.object_id) + ' REORGANIZE ' AS FIX_SQL
from 
sys.dm_db_index_physical_stats(db_id(N'[databasename]'), DEFAULT, DEFAULT, DEFAULT, DEFAULT) as a
inner join
sysindexes as b
on a.object_id = b.id 
and a.index_id = b.indid
order by a.avg_fragmentation_in_percent desc

Then, from the results set if any indexes are highly fragmented, run the FIX_SQL to repair them.

Points of Interest

This runs a lot faster on the database itself than from master in my experience.

History

  • 6th February, 2014: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Ireland Ireland
C# / SQL Server developer
Microsoft MVP (Azure) 2017
Microsoft MVP (Visual Basic) 2006, 2007

Comments and Discussions

 
SuggestionJust a few notes Pin
franop10-Feb-14 22:02
franop10-Feb-14 22:02 
GeneralRe: Just a few notes Pin
Duncan Edwards Jones10-Feb-14 22:11
professionalDuncan Edwards Jones10-Feb-14 22:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.