Friday, 15 March 2013

Logical fragmentation in SQL Server Indexes

My colleague Lawrence today discovered that a query we had that was taking over 2hrs to run (and still timing out), was due to a non clustered index being badly fragmented on the table in question.

To discover this fact he used the following queries, before rebuilding all indexes on the table, which then fixed the issue, and got the query coming back in 2 seconds.

--1. find index names
sp_helpindex 'dbo.MyTableName'

--2. show index logical fragmentation. Scan density should be above 97%
dbcc showcontig (MyTableName) WITH TABLERESULTS, ALL_INDEXES

--3. show when indexes were last rebuilt
Declare @dbid int
Select @dbid = db_id('Beacon')
Select objectname=object_name(i.object_id)
,, i.index_id
, o.create_date, o.modify_date
from sys.indexes i, sys.objects o
where objectproperty(o.object_id,'IsUserTable') = 1
--and i.index_id NOT IN
--(select s.index_id
--from sys.dm_db_index_usage_stats s
--where s.object_id=i.object_id and
--i.index_id=s.index_id and
--database_id = @dbid )
and o.object_id = i.object_id
and object_name(i.object_id)= 'MyTableName'
order by o.modify_date desc

No comments:

Post a Comment