Does the order of the columns in a WHERE clause effect performance?
e.g.
Say I put a column that has a higher potential for uniqueness first or visa versa?>
In theory any two queries that are equivalent should produce identical query plans. As the order of WHERE clauses has no effect on the logical meaning of the query, this should mean that the order of the WHERE clause should have no effect.
This is because of the way that the query optimiser works. In a vastly simplified overview:
JOIN or SELECT).The second step is done is a completely nieve way - it simply chooses the first / most obvious physical tree that it can, however in the 3rd step the query optimiser is able to look through all equivalent physical trees (i.e. execution plans), and so as long as the queries are actually equivalent it doesn't matter what initial plan we get in step 2, the set of plans all plans to be considered in step 3 is the same.
(I can't remember the real names for the logical / physical trees, they are in a book but unfortunately the book is the other side of the world from me right now)
See the following series of blog articles for more detail Inside the Optimizer: Constructing a Plan - Part 1
In reality however often the query optimiser doesn't have the chance to consider all equivalent trees in step 3 (for complex queries there can be a massive number of possible plans), and so after a certain cutoff time step 3 is cut short and the query optimiser has to choose the best plan that it has found so far - in this case not all plans will be considered.
There is a lot of behind the sceene magic that goes on to ensure that the query optimiser selectively and inteligently chooses plans to consider, and so most of the time the plan choses is "good enough" - even if its not the absolute fastest plan, its probably not that much slower than the theoretical fastest,
What this means however is that if we have a different starting plan in step 2 (which might happen if we write our query differently), this potentially means that a different subset of plans is considered in step 3, and so in theory SQL Server can come up with different query plans for equivalent queries depending on the way that they were written.
In reality however 99% of the time you aren't going to notice the difference (for many simple plans there wont be any difference as the optimiser will actually consider all plans). Also you can't predict how any of this is going to work and so things that might seem sensible (like putting the WHERE clauses in a certain order), might not have anything like the expected effect.