Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does order of T-SQL where statements matter?

Why, when opening a query like the following:

WHERE (statement1) AND ((statement2) OR (statement3))

does SSMS query designer refactor it into the following syntax:

WHERE (statement1) AND (statement2) OR (statement1) AND (statement3)

I assume it has something to do with how SQL server parses the query, running ands before ors?

Is there a general rule of how to the best order of statements for ultimate optimisation?

Having run my own tests, the 2nd query knocks 0.5ms off the processing time. Its small, I know, but would increase with the complexity of the query (still makes almost no difference) and I have a general interest in how SQL server works.

like image 461
jaypeagi Avatar asked Oct 10 '12 14:10

jaypeagi


2 Answers

It has nothing to do with the actual SQL execution. Unlike most languages you know, T-SQL does not have boolean operator short circuit1 and concepts like 'running ands before ors' make no sense, the order of evaluation is entirely driven by the query optimizer decisions and the may end up being completely different from what you write, or what you expect.

The expression rewrite you see seems to be entirely an artifact of the SSMS query designed internal parser.

1 Or better said the boolean short circuit cannot be determined imperatively by how you write the expression. Actual run time operator short circuit does happen, you just can't know if and when it will happen.

like image 126
Remus Rusanu Avatar answered Sep 23 '22 19:09

Remus Rusanu


In general, there is no guarantee for how SQL Server evaluates the Where clause. The optimizer will always try to find the most efficient way to execute the query.

To determine execution order, you should get an execution plan for your query (which you can get via SSMS). However, keep in mind this plan may change depending on what the optimizer thinks is the best query given current various statistics and resources.

like image 32
Randy Minder Avatar answered Sep 21 '22 19:09

Randy Minder