Skip to content

Instantly share code, notes, and snippets.

@hasokeric
Last active November 5, 2019 11:46
Show Gist options
  • Save hasokeric/516947b64f25d940548f2707611a8aa5 to your computer and use it in GitHub Desktop.
Save hasokeric/516947b64f25d940548f2707611a8aa5 to your computer and use it in GitHub Desktop.
Check SQL 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
select b.name as tablename, a.name as indexname, allow_row_locks, allow_page_locks, schema_name(b.schema_id)
from sys.indexes a
left join sys.objects b on a.object_id = b.object_id
left join sys.schemas c on b.schema_id = c.schema_id
where (a.allow_page_locks = 0) and a.name is not null and a.name <> '' and schema_name(c.schema_id) in ('Ice','Erp','CDC','IM')
select t.name TableName, i.rows Records
from sysobjects t, sysindexes i
where t.xtype = 'U' and i.id = t.id and i.indid in (0,1)
AND
t.name LIKE 'IM%'
order by i.rows desc;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment