This document discusses index fragmentation, including external and internal fragmentation. External fragmentation occurs when index pages are out of logical order, while internal fragmentation happens when index pages are not fully utilized. To identify fragmentation, the sys.dm_db_index_physical_stats dynamic management view can be queried. Results show statistics like fragmentation percentage and page usage. Fragmentation can be resolved by rebuilding or reorganizing indexes. Rebuilding completely drops and recreates an index while reorganizing physically reorders pages to reduce logical fragmentation without requiring free space.
11. How to identify? Scanning Modes : LIMITED – The fastest It scans all pages for a heap, but only the parent-level pages for an index, which are the pages above the leaf-level SAMPLED – Returns statistics based on a 1 percent sample of all the pages in the index or heap DETAILED Scans all pages and returns all statistics.
18. index_level - Current level of the index (The nonleaf levels of indexes are only processed when mode = DETAILED)
19.
20. Results (for Sampled and Detailed) avg_page_space_used_in_percent - Average percentage of available data storage space used in all pages (internal) Should be as high as possible ghost_record_count - Number of ghost records ready for removal by the ghost cleanup task (records are in the pages physically but not there logically due to deletion or update) version_ghost_record_count - Counts those records which are logically not in the table but cannot be deleted yet due to an open transaction using row versioning (running on snapshot isolation level)
25. reclaims disk space by compacting the pages based on the specified or existing fill factor setting
26. reorders the index rows in contiguous pagesALTER INDEX PK_Employee_EmployeeID ON HumanResources.Employee REBUILD CREATE UNIQUE CLUSTERED INDEX PK_Employee_EmployeeID ON HumanResources.Employee(EmployeeID ) WITH (DROP_EXISTING = ON)
31. Two phases: Compaction Defrag ALTER INDEX PK_Employee_EmployeeID ON HumanResources.Employee REORGANIZE
32. Rebuilding vs. Reorganizing Rebuild - Re-create the index internally again and when that has been achieved, it drops the existing index Statistics are re-computed Require free space Reorganize – Physically re-organizing the leaf nodes of the index Does not update statistics Swaps one page with another and therefore does not require free space Can free up some pages (compaction and defrag) Can remove logical fragmentation Not necessarily fix extent fragmentation (in which the previous and the next extents are physically contiguous)