Like grade school mathematics and the chicken and the egg, several fundamental concepts involving order of operations also apply to SQL statements. Take the following, for example:
SELECT columns FROM table WHERE a=1 AND b=2 OR a=2
|
I get confused reading that query, even after translating it to English:
GIVE ME the rows OUT OF this table WHEN a is 1 AND b is 2 OR a is 2
|
So, even with that straightforward English, which of these rows would meet the criteria?
id a b ------ ------- ------- 1 1 2 2 2 2 3 2 1 |
Tricky, isn't it? The SQL engine, like me, has a hard time determining which clause(s) the AND applies to, and which clause(s) the OR applies to. It really depends on what you mean by AND and what you mean by OR. You can separate and group distinct clauses by using parentheses. So, as an example, if you mean:
GIVE ME the rows OUT OF this table WHEN a is 1 *AND* b is 2, *OR* WHEN a is 2
|
Then your SQL query would be:
SELECT columns FROM table WHERE (a=1 AND b=2) OR a=2
|
And if you mean:
GIVE ME rows OUT OF this table WHEN a is 1 *AND* WHEN b is 2 *OR* a is 2
|
Then your SQL query would be:
SELECT columns FROM table WHERE a=1 AND (b=2 OR a=2)
|