SQL Server 2014 Index Fragmentation and Linkage checks.

To look at the amount of logical fragmentation in the leaf layer of the index

SELECT avg_fragmentation_in_percent, index_level, record_count, page_count
FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID(‘Table Name’), 2, NULL, ‘Detailed’)

 

SELECT
Fragmentation = ((COUNT(*)*1.00 – SUM(Case When NextPhysicalPageID = NextLogicalPageID then1 else 0 end))/COUNT(*)*1.00)*100,
PageCount = COUNT(*)
FROM

(
SELECT allocated_page_page_id, NextLogicalPageID = next_page_page_id,
NextPhysicalPageID = LEAD(allocated_page_page_id) over(partition by object_id, index_idorder by allocated_page_page_id)
FROM sys.dm_db_database_page_allocations(DB_ID(), OBJECT_ID(‘tablename’), 2, NULL,’DETAILED’)
WHERE page_type_desc = ‘INDEX_PAGE’ and page_level = 0
) a

 

 

 

showing page linkages and determine if this is fragmented. if the pages are matching with allocated page to next page, there is no indication of fragmentation.

else there is fragmentation.

 

SELECT
*, PageLinkMatch = Case When NextPhysicalPageID = NextLogicalPageID then 1 else 0 end
FROM
(
SELECT allocated_page_page_id, NextLogicalPageID = next_page_page_id,
NextPhysicalPageID = LEAD(allocated_page_page_id) over(partition by object_id, index_idorder by allocated_page_page_id)
FROM sys.dm_db_database_page_allocations(DB_ID(), OBJECT_ID(‘tablenamw’), 2, NULL,’DETAILED’)
WHERE page_type_desc = ‘INDEX_PAGE’ and page_level = 0
) a

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s