Search code examples
sqlsql-serverindexingsql-server-2000

SQL Server multiple index order optimization


I have a table with a nonclustered index1 on ID1 and ID2, in that order.

Select count(distinct(id1)) from table

returns 1

and Select count(distinct(id2)) from table has all the values of the table.

The querys to that table uses ... where id1= XX and id2 = XX

Could it make any performance improvement if I switch the order of the fields of index1 ?

I know it SHOULD be better but maybe: is it indifferent because id1 has only 1 value?


Solution

  • If I understand correctly, you are comparing these two statements:

    where id1= XX and id2 = XX
    

    Under most circumstances, this would use either an index on table(id1, id2) or table(id2, id1). The order of the comparisons in the where (or on) clauses has no impact on which indexes can be used.

    Whether you should include a column that has only a single value in the unique index is a different matter. There is a minor performance effect to having a more complex index -- the tree structure has to store more bytes for each key. However, the query:

    select count(distinct id2)
    from table
    where id1 = xx and idx = xx
    

    will actually run faster with a composite index than with a singleton index table(id2). The reason is that the composite index can be used to entirely satisfy the query (in the jargon, it is a "covering index for the query"). The singleton index would need to look up the value of id1 in the table data, which requires extra processing.