I'm having trouble figuring out the evaluation order of boolean predicates in SQL.
Consider the following selection predicate over our (imaginary) car database:
WHERE
make='Honda' AND model='Accord' OR make='VW' AND model='Golf';
I know that AND has precedence over OR, however I'm confused if this expression would be evaluated as follows:
((make='Honda' AND model='Accord') OR make='VW') AND model='Golf';
or as:
(make='Honda' AND model='Accord') OR (make='VW' AND model='Golf');
Or something completely different?!
Your help if very much appreciated.
if you are unsure about the evaluation order (me too, btw), you always can set parentheses as needed. So you "define" your evaluation order yourself, and even if the sql interpreter changes its evaluation behaviour, the result will still be the same.
I know that this does not really answer your question, but why bother with evaluation order, if you can define it yourself with the use of ()?
I believe the order will be
Thats means:
Thats because in most DBMS
AND
is the upper hand overOR
EDIT: Yes, condition have also precedence from left to right, but this is the same as order by:
Here col1 get presendence first, then col2, and then col 3. Same goes for our situtation, first presendence is
AND over OR
, second one isLEFT to RIGHT
This should be evaluated like
Explanation: In SQL server
AND
has precedence overOR
and there fore you can imagine AND parts to be inside parenthesis and evaluated first and after them ORDetails based on your comments
L2R parsing
WHERE (make='Honda' AND model='Accord') OR make='VW' AND model='Golf';
because first all ANDs and leftmost
WHERE
result1OR (make='VW' AND model='Golf');
because first all ANDs
WHERE
result1OR
result2;
finally OR
R2L parsing
WHERE make='Honda' AND model='Accord' OR (make='VW' AND model='Golf');
because first all ANDs and rightmost AND first
WHERE (make='Honda' AND model='Accord') OR
result1;
because first all ANDs over OR
WHERE
result2OR
result1;
finally OR
So in both cases the condition evaluates to
So I evaluated all three expressions in below query
And the results show that
result =result1
all the time, proving that it is evaluated asSee sqlfiddle demo
I second thoughts of people who answered above. Since AND has precedence over OR, all the AND expressions should be evaluated first then their results will be evaluated with OR i.e. it should be