Logical Operators (AND, OR, NOT)
Logical operators combine multiple conditions in WHERE clauses. AND requires all conditions to be true. OR requires at least one. NOT reverses a condition. Operator precedence (NOT > AND > OR) can cause subtle bugs — always use parentheses.
Logical Operator Rules
- AND — both sides must be TRUE
- OR — at least one side must be TRUE
- NOT — reverses TRUE to FALSE, FALSE to TRUE
- Precedence: NOT > AND > OR
- WHERE a OR b AND c → WHERE a OR (b AND c) — AND binds tighter!
- Always use parentheses when mixing AND and OR
- NULL in logic: NULL AND TRUE = NULL, NULL OR TRUE = TRUE
AND, OR, NOT Examples
-- AND: both conditions must be true
SELECT name, price, stock
FROM products
WHERE price > 50 AND stock > 100;
-- Result: Headphones (89.99, 200)
-- OR: either condition is true
SELECT id, status FROM orders
WHERE status = 'pending' OR status = 'shipped';
-- NOT: reverses condition
SELECT name FROM products WHERE NOT name = 'Laptop';
-- Mixing AND + OR — use parentheses!
SELECT name, price FROM products
WHERE (price < 100 OR price > 900) AND stock > 0;
-- Correct: parentheses around OR
-- Dangerous (no parentheses)
-- WHERE price < 100 OR price > 900 AND stock > 0
-- Reads as: price < 100 OR (price > 900 AND stock > 0)
-- Different meaning!
-- Multiple AND conditions
SELECT * FROM orders
WHERE user_id = 1
AND status != 'cancelled'
AND total_amount > 0;Quick Quiz
Tip
Tip
Practice Logical Operators AND OR NOT in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Inner query runs first, results used by outer query. CTEs are often more readable.
Common Mistake
Warning
A common mistake with Logical Operators AND OR NOT is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready sql code.
Practice Task
Note
Practice Task — (1) Write a working example of Logical Operators AND OR NOT from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Key Takeaways
- Logical operators combine multiple conditions in WHERE clauses.
- AND — both sides must be TRUE
- OR — at least one side must be TRUE
- NOT — reverses TRUE to FALSE, FALSE to TRUE