tags:

views:

47

answers:

2

When I declare a clustered index, specifying: column1, column2 and column3 in this order - do I need to use the columns in that same order?

For example, will this use the clustered index mentioned earlier to update multiple rows:

 UPDATE Table1     
   WHERE column3 = 1 
      AND column2 = 1 
      AND column1 = 1
+3  A: 

The order you use declare the items in the Where clause, as you have stated, should not make a difference as to whether the database server is able to use an index which covers those columns.

Thomas
My co-worker just told me that I should use the index columns the same sequence as I declare them. But I haven't found any document for this requirement.
Tony Bao
@Tony Bao: Order in the query is irrelevant, but order in the covering index does matter.
OMG Ponies
@Tony Bao - The query engine is smart enough to know that the columns referenced map to an existing index. The order you state the columns does not make a difference. It is easy enough to test. Create a query that uses the index and change the order of the columns and see if the execution plan changes (hint: it won't).
Thomas
OMG Ponies and Thomas: thanks a lot.
Tony Bao
@Tony Bao: you're coworker is wrong - it doesn't matter at all. If you have a compound index with three columns, the only thing that matters is that you specify all three columns in your WHERE clause - but the order is irrelevant.
marc_s
+1  A: 

It's true that when you're checking for exact equality, that order does not matter.

But that's not to say that the order in the index does not matter -- perhaps this is what your co-worker was trying to say. For example, if I have a table:

PersonID  FName    LName
--------  -------  -----
1         John     Smith
2         Bill     Jones
3         Frank    Smith
4         Jane     Jackson
...
(assume a significantly large table)

and I define an index on it in the order (LName, FName), that index will necessarily perform differently than an index defined in the order (FName, LName), depending on what the query is.

For example, for the query: SELECT * FROM People WHERE LName = 'Smith', you will most likely get a better plan for the first type of index than for the second type.

Likewise, SELECT * FROM People WHERE FName = 'John' will perform better with the second index structure over the first.

And SELECT * FROM People WHERE FName = 'John' AND LName = 'Smith' will perform identically no matter what order the index is created.

Dave Markle