SQL order of operations for logical operands
SQL order of operations for logical operands
I inherited some some bad SQL code (zero documentation and I'm missing the original requirements). In the where clause, it has the following:
A OR B AND C AND D OR E
From my knowledge of logical operands, my assumption is that SQL would compile this as:
A OR (B AND C AND D) OR E
Is that correct?
I have a feeling the intent was
(A OR B) AND C AND (D OR E)
and I will need to speak with those that requested this project in the first place, as I haven't seen the original requirements.
If you are going to add parentheses, then the correct version would be:
(A OR ((B AND C) AND D)) OR E
. This is semantically equivalent to your second version.– Gordon Linoff
Aug 22 at 18:08
(A OR ((B AND C) AND D)) OR E
Documentation for condition precedence, showing that you are right as
AND
has higher precedence than OR
.– Alex Poole
Aug 22 at 18:42
AND
OR
@GordonLinoff - No, the version you propose is not equivalent to the OP's second version. And it is impossible to know what the "correct" version is, without knowing the intent (the requirement).
– mathguy
Aug 22 at 18:53
1 Answer
1
You are correct. In the absence of parenthesis this should be interpreted as:
A OR (B AND C AND D) OR E
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Your understanding of boolean operator precedence is exactly right: AND is stronger than OR, exactly like multiplication is vs. addition. Your guess as to the intent is probably also 100% correct (meaning that the condition is written incorrectly) but you won't know without asking those who requested the project.
– mathguy
Aug 22 at 18:07