With this query I can list index fragmentation:

SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
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

But sometimes, it's listed like this:

enter image description here

What does this mean? is the table fragmented?

And, while I'm here, I would like to ask another question.

I'm using a job to reorganize indexes. All of them are just being reorganized, because this database is running at full speed 24/7 and I can't use rebuild because of locks.

What is the best way to use rebuild\reorganize in this situation? is Hallengren a better solution in this case? if im not mistaken, if the index can't be locked, it will just reorganize it.



Dont try to reinvent the wheel as there is a cost to reinventing it.

Use Ola's maintenance scripts - they are tested well enough and follow best practice. You can even use LockTimeout in Ola's solution.

I would not worry on the fragmentation levels where the page count is less than 5K.

What is the best way to use rebuild\reorganize in this situation?

Do the index maintenance during less activity or maintenance time.

| improve this answer | |
  • Thanks kim. I will use it. but, what about the tables with AVG_fragmentation with null indexes? is this table fragmentation? I never heard it before and I would like to study it a little more. – Racer SQL Sep 19 '16 at 13:33
  • Did you check if they are Heaps or not ? – Kin Shah Sep 19 '16 at 13:36
  • Yes I checked it. they have some indexes. ( one of them has 6 indexes ). Some of them are being shown below the list with <5% fragmentation. I found A question here, where it said to "create a clustered index to reorganize the HEAP, and then drop it ". but i think it's not the case here. – Racer SQL Sep 19 '16 at 13:39
  • Hmmm having indexes doesn't mean it's not a heap though. You can have indexes on a heap. Kin was specifically asking to see if you have a 'clustered' index on there. Can you let us know? Thanks. – Ali Razeghi Sep 19 '16 at 16:57
  • Are you using SQL Server 2014 Enterprise Edition? That gives you additional options for defragmentation. – RLF Sep 19 '16 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.