Topic 10 of 52
Logical Operators
Overview
Real-world queries rarely have just one filter. You often need to chain multiple conditions together to find the exact subset of data you need. The AND, OR, and NOT logical operators allow you to build complex boolean logic directly into your WHERE clause.
Syntax
sql
-- 1. AND: BOTH conditions must be True
SELECT * FROM cars
WHERE make = 'Toyota' AND year >= 2020;
-- 2. OR: AT LEAST ONE condition must be True
SELECT * FROM users
WHERE plan = 'Pro' OR plan = 'Enterprise';
-- 3. NOT: Reverses the boolean logic
SELECT * FROM employees
WHERE department NOT IN ('HR', 'Finance');
-- 4. PARENTHESES: Explicitly control the order of operations!
SELECT * FROM products
WHERE category = 'Electronics'
AND (price < 50 OR stock > 100);Common Pitfalls
- Forgetting parentheses when mixing
ANDandOR. In SQL,ANDhas higher mathematical precedence thanOR(just like multiplication beats addition).WHERE A AND B OR Cis evaluated as(A AND B) OR C. If you meantA AND (B OR C), your query will silently return massively incorrect data without throwing an error. - Double negatives.
NOT (price <= 50)is harder to read thanprice > 50. Simplify your logic.
Interview Questions
Q:
Evaluate this clause:
WHERE status = 'Active' OR status = 'Pending' AND age > 30. Who gets included?A:
Because AND evaluates first, it returns ANYONE who is 'Active' (regardless of age), PLUS anyone who is both 'Pending' AND over 30. This is almost certainly a bug caused by missing parentheses.
Real-World Example
A complex filter for a real-estate search engine.
example
sql
SELECT property_id, address, price
FROM listings
WHERE city = 'Seattle'
AND price BETWEEN 500000 AND 800000
AND (bedrooms >= 3 OR has_basement = TRUE)
AND status != 'Sold';Check Your Knowledge
Test your understanding of Logical Operators with these quick questions.