I was just reading from here https://stackoverflow.com/questions/6187904/hard-and-fast-rule-for-include-columns-in-index
regarding included columns.
n index is typically
CREATE INDEX <name> ON <table> (KeyColList) INCLUDE (NonKeyColList)
Where:
- KeyColList = Key columns = used for row restriction and processing
WHERE, JOIN, ORDER BY, GROUP BY etc - NonKeyColList = Non-key columns = used in SELECT and aggregation (e.g. SUM(col)) after selection/restriction
Now let’s say my query is :
SELECT Col7 ,
Col8 ,
Col9 ,
Col10
FROM [MyTable] M
WHERE Col1 =1
AND Col2=2
AND Col3=3
AND Col4=4
AND Col5=5
AND Col6=6
GROUP BY Col7 ,
Col8 ,
Col9 ,
Col10
ORDER BY Col8
What should be the index for me here in this case? and second case where Col7 is primary key
I would think you would want something like:
You’re filtering on
Col1-Col6and retrievingCol7-Col10. Not sure how this will work with thegroup by, though. You may want to rewrite it as aDISTINCTsince the exec plan and results are the same but it will be more readable.If
Col7is a primary key and has a clustered index, you can leave this like it is.Col7will be included in the index without being specifically mentioned as a cluster key is in every non-clustered index as a row identifier, but keeping it in won’t hurt as SQL will ignore it.