Logical operators (AND OR NOT)
AND, OR and NOT combine conditions, with parentheses controlling the order.
In this page:
Syntax
WHERE condition1 AND condition2
WHERE condition1 OR condition2
WHERE NOT condition
Logical operators (AND OR NOT)
AND requires both conditions, OR requires at least one, and NOT reverses a condition. AND is evaluated before OR, so use parentheses when mixing them. Any comparison with NULL yields NULL (unknown), which WHERE treats as false.
Note:
Add parentheses whenever you mix AND and OR.
Example: Logical operators (AND OR NOT)
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, city TEXT, age INTEGER);
INSERT INTO users VALUES (1, 'Ada', 'London', 36), (2, 'Bob', 'Oslo', 25), (3, 'Cy', 'Oslo', 41), (4, 'Di', 'Rome', 30);
SELECT name FROM users WHERE city = 'Oslo' AND age > 30;
SELECT name FROM users WHERE city = 'Rome' OR age > 40;
SELECT name FROM users WHERE NOT city = 'Oslo';
SELECT name FROM users WHERE (city = 'Oslo' OR city = 'Rome') AND age < 35;
-- Output:
-- name
-- Cy
-- name
-- Cy
-- Di
-- name
-- Ada
-- Di
-- name
-- Bob
-- Di
Login to try C/C++/Java/PHP code in the editor
Related Topics
Common Mistakes
- Forgetting AND has higher precedence than OR
- Ignoring NULL in NOT conditions
- Overly long unparenthesised conditions
Chapter Summary
- AND both, OR either, NOT reverse
- AND binds tighter than OR
- Use parentheses to be explicit
- NULL makes a condition unknown
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: