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.
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.