How can I optimize this query?
You can make a covering index:
CREATE INDEX ix_table1_456__123 ON table1 (col4, col5, col6) INCLUDE (col1, col2, col3)
and the query will not even have to do a table lookup.
If I add indexes for each column in the where clause, would that make any difference?
This will most probably improve the query compared to not having indexes at all, but creating the composite index with covering will most probably be better.
However, if each of your columns has high cardinality (that is it is UNIQUE
or close to it), then creating individual indexes may even improve the query compared to the composite index.
This is especially true if some of the columns is large in size (like a VARCHAR(400)
) and another, small column has high cardinality.
If I have 10 columns in where clause, should all of those 10 columns have index in them?
If you have 10
columns, there's, as I said above, a tradeoff between the increased key size (which degrades performance) and increased selectivity.
If, say, the first 3
columns are unique or almost unique, then adding the additional columns won't increase selectivity but will increase the key size.
The index will get larger in size which will require extra time to search in it.
You should not create the index on all 10
columns if 3
columns offer selectivity which is high enough, since traversing a larger index will be more expensive than reading some extra keys.
You may want to read this article in my blog: