I Want To Create Index In SQL Server 2008 R2 in Column1 and Column2
What is the difference of below query:
-
Not include
CREATE NONCLUSTERED INDEX [IX_1] ON [dbo].[MyTable] ( [Column1] ASC, [Column2] ASC ) ON [PRIMARY] -
Or include:
CREATE NONCLUSTERED INDEX [IX_2] ON [dbo].[MyTable] ( [Column1] ASC ) INCLUDE ([Column2]) ON [PRIMARY]
In the first one
Column2gets 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 byColumn1but avoid the need to go back to the base table (bookmark lookup/key lookup) to retrieve the value forColumn2.i.e. it makes index2 “covering” for queries such as
And it also covers queries such as
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
Column1then needing to evaluate all matching rows at the index leaf level to see if they meet theColumn2predicate). IfColumn2is never used as a search predicate against that index and your queries against that index wouldn’t benefit from havingColumn2ordered then it should be added as anINCLUDE-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
Column2is (part of) the clustered index key it will still be added there anyway for a non clustered index not created with theUNIQUEoption.