SQL AND / OR Order of Operations
When is comes to SQL and a series of AND and OR directives in the WHERE clause, the order of operations can be confusing. I am not sure what the rules are to this, but this is what my personal experience has shown me. Even with no parenthesis, OR clauses create the same effect as adding parentheses. So for instance, the SQL query below:
 SELECT
 name
 FROM
 tag
 WHERE
 1 = 0
 AND
 1 = 0
 OR
 1 = 1
 AND
 1 = 0
 AND
 2 = 2
 OR
 1 = 1
 AND
 2 = 2
... seems to be rewritten to be the same as:
 SELECT
 name
 FROM
 tag
 WHERE
 (
 1 = 0
 AND
 1 = 0
 )
 OR
 (
 1 = 1
 AND
 1 = 0
 AND
 2 = 2
 )
 OR
 (
 1 = 1
 AND
 2 = 2
 )
Notice that the OR directive seem to just group the other directives (AND) in the where clause. That is why changing the last AND 2 = 2 to AND 2 = 3 will turn the whole WHERE clause to be untrue. So, even though the following looks like it would be true due to the OR 1 = 1 directives:
 SELECT
 name
 FROM
 tag
 WHERE
 1 = 0
 AND
 1 = 0
 OR
 1 = 1
 AND
 1 = 0
 AND
 2 = 2

  Might think this OR directive will make everything true
  but it does not (see below).
 OR
 1 = 1

 AND
 2 = 3
... it turns out to be false when you take in the behindthescenes parentheses into account:
 SELECT
 name
 FROM
 tag
 WHERE
 (
 1 = 0
 AND
 1 = 0
 )
 OR
 (
 1 = 1
 AND
 1 = 0
 AND
 2 = 2
 )

  This OR directive no longer returns true since you can see
  that it is not just OR 1 = 1, but in fact, it is an OR'ing
  of two separate AND directives that do not return true.
 OR
 (
 1 = 1
 AND
 2 = 3
 )
So, as far as order of operations go, it's not so much about AND and OR directives in the WHERE statement, but rather, how the behindthescenes parentheses will group the nonOR directives. In order for this to be clear, I would suggest always using the parenthesis when using AND and OR statements. Furthermore, even if it is not required, the parenthesis will make it easier for anyone else looking at your code to understand what is going on.
Looking For A New Job?
Ooops, there are no jobs. Post one now for only $29 and own this real estate!
Reader Comments
It's simple from the boolean logic point of view. AND is multiplication whereas OR is addition.
AND:
1 AND 1 = 1 <=> 1 * 1 = 1
0 AND 1 = 0 <=> 0 * 1 = 0
etc.
OR:
0 OR 0 = 0 <=> 0 + 0 = 0
0 OR 1 = 1 <=> 0 + 1 = 1
etc.
The only exception is
1 OR 1 = 1 <=> 1 + 1 = 1
but it makes sense because there is no value above 1.
The ordering of operations is the same as the order of simple arithmetic.
@Unicode,
I'm sorry, but explaining that in terms of mathematical PEMDAS is.... brilliant!! Thanks!
Thanks a lot Ben for this article. It cleared my confusion on whether AND operations are performed first or OR when there's no parenthesis. :)
The logic precedence in queries is NOT, AND, OR.
You can read more on http://technet.microsoft.com/enus/library/ms186992%28v=sql.105%29.aspx
@Unicode, totally makes sense!
@Ben, awesome article. Simple and powerful as heck.