Skip to main content

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

  1. NOT, evaluated first;
  2. AND, evaluated second;
  3. 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:

  1. First applies NOT city = 'Kyiv';
  2. Then checks AND department = 'IT';
  3. 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:

OperatorPrecedenceUsage example
NOT1NOT city = 'Kyiv'
AND2age > 18 AND city = 'Kyiv'
OR3city = 'Kyiv' OR city = 'Lviv'

Summary:

  • SQL always follows this precedence: NOTANDOR.
  • 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.