How do you work with logical operator precedence?
The precedence of logical operators (NOT, AND, OR) determines the order SQL checks conditions in a WHERE filter.
If that order isn't set explicitly, SQL follows its own rules, not your intended logic.
The standard order of precedence
NOT, evaluated first;AND, evaluated second;OR, evaluated last.
An example without parentheses
sql
SELECT *
FROM employees
WHERE NOT city = 'Kyiv' AND department = 'IT' OR salary > 80000;SQL evaluates this as:
- First applies
NOT city = 'Kyiv'; - Then checks
AND department = 'IT'; - And only then
OR salary > 80000.
That is, it selects every IT employee not from Kyiv or everyone whose salary is over 80,000, even if they're from Kyiv and not in IT.
How to change the precedence
To make SQL evaluate conditions in the order you want, use parentheses:
sql
WHERE NOT (city = 'Kyiv' AND department = 'IT')Now NOT applies to the whole expression inside the parentheses.
Another example:
sql
WHERE (city = 'Kyiv' OR city = 'Lviv') AND salary > 70000;The cities get checked first, then the salary filter.
In short:
| Operator | Precedence | Usage example |
|---|---|---|
NOT | 1 | NOT city = 'Kyiv' |
AND | 2 | age > 18 AND city = 'Kyiv' |
OR | 3 | city = 'Kyiv' OR city = 'Lviv' |
Summary:
- SQL always follows this precedence:
NOT→AND→OR. - To set your own order, add parentheses.
- It's better to always use parentheses in complex filters, it keeps the code readable and predictable.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.