Difference of create Index by using include column or not using

前端 未结 1 1812
梦毁少年i
梦毁少年i 2021-01-01 14:36

I Want To Create Index In SQL Server 2008 R2 in Column1 and Column2 What is the difference of below query:

  1. Not include

    CREATE NONCLUSTERED I         
    
    
            
1条回答
  •  醉梦人生
    2021-01-01 15:24

    In the first one Column2 gets added to the index key. In the second one it might not (*) get added to the key in which case it will only appear in the index leaf pages. This can allow the index to be searched by Column1 but avoid the need to go back to the base table (bookmark lookup/key lookup) to retrieve the value for Column2.

    i.e. it makes index2 "covering" for queries such as

    SELECT Column1,Column2
    FROM [dbo].[MyTable] 
    WHERE Column1 = 'X'
    

    And it also covers queries such as

    SELECT Column1,Column2
    FROM [dbo].[MyTable] 
    WHERE Column1 = 'X' AND Column2 = 'Y' 
    

    But index1 may well perform better for the second query as it can seek on the two columns directly (as opposed to only being able to search on Column1 then needing to evaluate all matching rows at the index leaf level to see if they meet the Column2 predicate). If Column2 is never used as a search predicate against that index and your queries against that index wouldn't benefit from having Column2 ordered then it should be added as an INCLUDE-d column to keep the size of the key down and reduce the number of pages in the index.

    (*) The reason I say "might not" above is because if Column2 is (part of) the clustered index key it will still be added there anyway for a non clustered index not created with the UNIQUE option.

    0 讨论(0)
提交回复
热议问题