Reputation: 3111
I am trying to work out how SQL queries are run and have hit a bit of a stumbling block.
If a where clause akin to the below is used:
A OR B AND C
This could mean either of the below
(A OR B) AND C
or
A OR (B AND C)
In the majority of cases the results will be the same, but if the set to be queried contains solely {A}, the first variant would return an empty result set and the second would return {A}. SQL does in fact return the 1 result.
Does anyone know (or have links to) any insight that will help me understand how queries are built?
Ketchup
Upvotes: 1
Views: 112
Reputation: 57093
In the knowledge (from documentation) that AND
has a higer precedence than OR
, you should aim to write predicates for WHERE
clauses in conjunctive normal form ("a seires of AND
clauses").
If the intention is
( A OR B ) AND C
then write it thus and all is good.
However, if the intention is
A OR ( B AND C )
then I suggest you apply the distributive rewrite law that results in conjunctive normal form i.e.
( P AND Q ) OR R <=> ( P OR R ) AND ( Q OR R )
In your case:
A OR ( B AND C ) <=> ( A OR B ) AND ( A OR C )
Upvotes: 2
Reputation: 3183
For SQL-Server (which is your tag) here is the precedence http://msdn.microsoft.com/en-us/library/ms190276.aspx but.. If you're worried about the exact result set given you should indeed start working with () subsets.
Upvotes: 0
Reputation: 7529
The order is the following according to MSDN:
~ (Bitwise NOT)
(*) (Multiply), / (Division), % (Modulo)
(+) (Positive), - (Negative), + (Add), (+ Concatenate), - (Subtract), & (Bitwise AND), ^ (Bitwise Exclusive OR), | (Bitwise OR)
=, >, <, >=, <=, <>, !=, !>, !< (Comparison operators)
NOT
AND
ALL, ANY, BETWEEN, IN, LIKE, OR, SOME
= (Assignment)
Upvotes: 2