Inside of SQL Server Indexes
Slava Murygin @SlavaSQL SlavaSQL.BLOGSPOT.com
This presentation does not cover: Compressed Indexes Spatial Indexes Full-Text Indexes XML Indexes In-Memory Indexes
SQL Database Structure Database File SQL DB Extent = 8 Pages Pages 8 16 1 Page = 8 Kb 1 Extent = 64 Kb 24 64 Kb is Standard Memory Block 32
Page Structure
Table Structure. The Heap. The Heap: Table without Clustered Index. Index Allocation Map 1 IAM Page 2 3 4 . . . N N+1 N+2 Data Pages
Why do we need Indexes To reduce number of IO during data extraction Support sorting operations Establish uniqueness within a column or set of columns Indexes: Exchange Money Disk Space for Time.
Index B-Tree Structure Root Page Intermediate Pages Leaf Pages
Two Classes of indexes: Clustered Indexes Can be only one per table (and must be unique) Non-Clustered Indexes Can be multiple of different types Both can be Unique and/or Composite
Next page Previous Page Clustered Index AAA BAA CAA Root Page AAA ABA ACA BAA BBA BCA Intermediate Pages CAA CBA CCA Next page Previous Page AAA AAB AAC ABA ABB ABB+8 ACA ACB ACC BAA BAB BAC BBA BBB BBC BCA BCB BCC CAA CAB CAC CBA CBB CBC CCA CCB CCC Leaf Pages = Data Pages
Clustered Index - Details Clustered Index keep uniqueness or build it if it does not exist, which requires extra space on all levels. Leaf Level of Clustered Index IS actual Data. When we build Clustered Index we copy whole data set to a new place. Recommendations for Clustered Index: - Start from most used and diverse columns; - Cover the most expensive queries; - Keep Clustered Index as short as possible.
Page Splits Updating variable sized columns Inserting records within a range AAA-X ABA-Y ACA-Z INSERT “ABBC” AAA-X ABA-Y1 ABBC-Y2 ACA-Z X AAA AAB AAC Y ABA ABB ABC Z ACA ACB ACC X AAA AAB AAC Y1 ABA ABB Y2 ABBC ABC Z ACA ACB ACC
Fill Factor and PAD_INDEX AAA AAC ABB ACA AAA AAB AAC ABA ABB ABC ACA ACB Fill Factor: Exchange Space for Time
Non-Clustered Indexes Regular Non-Clustered Index: - Filtered; - Covering; - With Included Columns; Indexed Views (materialized views) Special Indexes: - Spatial; - Compressed; - XML; - Full-Text; - In-Memory; - Columnstore;
Non-Clustered Indexes at Work Use Clustered index to retrieve a data If there is no Clustered index they address data directly
Covering Indexes Space for Time Do not require to go to a data Level or Clustered Index
Indexes with Included Columns Reduce Index size Help to avoid some Index limits
Filtered Indexes Reduce Index size
Querions? @SlavaSQL SlavaSQL.BLOGSPOT.com