π FilteringbeginnerCommonly used
How to use AND, OR and NOT in SQL
Combine multiple filter conditions in a WHERE clause.
AND β all conditions must matchAll databases
SELECT name, age, country
FROM users
WHERE country = 'Kenya'
AND age >= 18
AND active = true;Every condition must be true for a row to be included.
OR β any condition can matchAll databases
SELECT name, country
FROM users
WHERE country = 'Kenya'
OR country = 'Nigeria'
OR country = 'Ghana';A row is included if any condition is true.
For multiple OR conditions on the same column, use IN instead.
NOT β negate a conditionAll databases
SELECT name, country
FROM users
WHERE NOT (country = 'Kenya' OR country = 'Nigeria');Excludes rows where either condition is true.
Operator precedence β use parenthesesAll databases
-- AND is evaluated before OR β this may not do what you expect:
SELECT * FROM orders
WHERE status = 'pending' OR status = 'failed' AND amount > 100;
-- Be explicit with parentheses:
SELECT * FROM orders
WHERE (status = 'pending' OR status = 'failed')
AND amount > 100;AND has higher precedence than OR. Always use parentheses when mixing AND and OR to make the intent clear.
This is one of the most common SQL bugs.
Common Mistakes
- βAND/OR precedence β AND binds tighter than OR. Always use parentheses when mixing them.
- βWriting WHERE x = 1 OR 2 β this does not work. Write WHERE x = 1 OR x = 2.