After Using the “Display Estimated Execution Plan” on two queries, I ended up creating two indexes as follows:
CREATE NONCLUSTERED INDEX IX_ABC ON dbo.my_table
(colA,colB,colC)
and
CREATE NONCLUSTERED INDEX IX_ABC ON dbo.my_table
(colA,colD,colE)
I noticed that creating just one index (replacing the above two):
CREATE NONCLUSTERED INDEX IX_ABC ON dbo.my_table
(colA,colB,colC,colD,colE)
also optimizes my queries.
So my question is, is it correct that the index with all the columns optimizes as well as two separate ones or is one method preferable to the other.
Thanks
To answer your question simply, order is important (think of a multi-level tree) so a combined index will not help with a query that only searches ColA, ColD, and ColE and not ColB and ColC.
So, for example, if you had a query like
SELECT colA, colD, colEFROM dbo.my_table
WHERE colA = 1 AND colD = 2
the second (combined) index would help somewhat (with the ‘ColA’ predicate) but the database would still have to scan the remaining results for colD = 2.
On the other hand, the combined index will take up less overall space, and have less of an impact on updates to column A, so you will have to weigh the tradeoffs.