Click here to Skip to main content
Click here to Skip to main content

Find and fix fragmented indexes

, 5 Feb 2014
Rate this:
Please Sign up or sign in to vote.
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:-

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.

License

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

About the Author

Duncan Edwards Jones
Software Developer (Senior)
Ireland Ireland
C# / SQL Server developer
Microsoft MVP 2006, 2007
Visual Basic .NET
Follow on   Twitter   LinkedIn

Comments and Discussions

 
SuggestionJust a few notes Pinmemberfranop10-Feb-14 22:02 
GeneralRe: Just a few notes PinmemberDuncan Edwards Jones10-Feb-14 22:11 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 6 Feb 2014
Article Copyright 2014 by Duncan Edwards Jones
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid