AND, OR, NOT
Real-world filters rarely stop at a single condition.
AND, OR, and NOT let you combine and negate conditions inside a WHERE clause to express exactly the rows you want.AND — every condition must be true
AND requires both conditions
SQL
SELECT first_name, last_name FROM employees WHERE department = 'Engineering' AND salary > 90000;
OR — at least one condition must be true
OR requires at least one condition
SQL
SELECT first_name, last_name FROM employees WHERE department = 'Engineering' OR department = 'Data Science';
NOT — negating a condition
NOT flips the result of a condition
SQL
SELECT first_name, last_name FROM employees WHERE NOT department = 'Sales';
This is equivalent in effect to
department != 'Sales', but NOT becomes especially useful in front of more complex conditions, like NOT (a AND b) or NOT EXISTS (...).Operator precedence
When
AND and OR appear in the same condition, AND is evaluated first — it binds more tightly than OR, similar to how multiplication binds tighter than addition in arithmetic.Operator | Precedence |
|---|---|
NOT | Highest — evaluated first |
AND | Middle — evaluated before OR |
OR | Lowest — evaluated last |
A query that doesn't do what it looks like it does
Without parentheses, this query looks like it should return employees who are either in Engineering with a high salary, or in Sales with a high salary. It does not:
Ambiguous without parentheses
SQL
SELECT first_name, last_name, department, salary FROM employees WHERE department = 'Engineering' OR department = 'Sales' AND salary > 100000;
Because
AND binds tighter than OR, the database actually reads this as: return every Engineering employee (regardless of salary), *or* any Sales employee earning over 100,000. That almost certainly is not the intended logic. The fix is to make the grouping explicit with parentheses:Parentheses make the intent explicit
SQL
SELECT first_name, last_name, department, salary FROM employees WHERE (department = 'Engineering' OR department = 'Sales') AND salary > 100000;
This version correctly requires the employee to be in Engineering or Sales, and to earn over 100,000. When in doubt, add parentheses — they cost nothing and remove all ambiguity, for the database and for the next person reading the query.