🌱BeginnerFiltering & Sorting
Logical Operators: AND, OR, NOT
Combine multiple conditions with AND, OR, and NOT in WHERE clauses.
Overview
AND, OR, and NOT are the logical operators for combining boolean conditions. AND requires both conditions to be true. OR requires at least one to be true. NOT negates a condition. They follow standard three-valued logic: when NULL is involved, the result can be TRUE, FALSE, or NULL.
Operator precedence: NOT has the highest precedence, then AND, then OR. This means A OR B AND C is interpreted as A OR (B AND C). Use parentheses liberally to make intent explicit and avoid bugs.
Key Points
- •AND both conditions must be TRUE
- •OR at least one condition must be TRUE
- •NOT negates a boolean expression
- •Precedence: NOT > AND > OR (use parentheses to be explicit)
- •NULL AND TRUE = NULL; NULL OR TRUE = TRUE; NOT NULL = NULL
Examples
Combining conditions
-- AND: both must be true
SELECT * FROM products WHERE price > 10 AND category = 'Tech';
-- OR: at least one must be true
SELECT * FROM users WHERE role = 'admin' OR role = 'superuser';
-- NOT: negate a condition
SELECT * FROM orders WHERE NOT status = 'cancelled';
-- Equivalent: WHERE status <> 'cancelled'
-- Parentheses for clarity
SELECT * FROM orders
WHERE (status = 'pending' OR status = 'processing')
AND total > 100;Common Mistakes
- Forgetting parentheses: WHERE a = 1 OR b = 2 AND c = 3 is parsed as WHERE a = 1 OR (b = 2 AND c = 3) use parentheses to be clear.
Exercises
Write SQL to solve each exercise. Your progress is saved automatically.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4