I have a table with primary key, and two foreign keys, where both allows NULLS.
When I create indexes separately for each two columns, query running about 2-3 seconds and return around 300000 rows.
When I create composite non-clustered index for that two columns, query running around 10 minutes for same number of rows.
It’s important to notice that two columns appear in WHERE condition and works with OR clause, like this:
Select
SomeColumn
From
SomeTable
Where
FirstColumn = x OR SecondColumn = x
Platform on which query was executed is SQL 2008 R2.
Why there is such a difference in execution time in that two cases?
If you have two separate indexes, and only those two columns are in the
WHEREclause then the optimizer can use them both efficiently to determine the required rows (presumably anINDEX SEEK).A composite index is not that good as composite indexes are first sorted on the first index column, then the second, and so on. So it’s just useful for the first column in your
ORcondition, like you got. To determine the rows for the second column the optimizer would have to scan the complete table as it doesn’t have suitable index.If you got a large table with this scenario, then the single indexes will be usually faster for simple queries like you asked. It actually also depends on the selected columns, query complexity, covering indexes and so on.
I had this problem myself. See: Query performance of combined index vs. multiple single indexes vs. fulltext index for reference.