How to filter data with WHERE clause
· Category: SQL & Databases
Short answer
The WHERE clause follows FROM and filters rows by evaluating a boolean expression for each row.
Steps
- Basic equality:
SELECT * FROM products WHERE category = 'Electronics'; - Range checks:
SELECT * FROM orders WHERE order_date BETWEEN '2025-01-01' AND '2025-01-31'; - List membership:
SELECT * FROM customers WHERE country IN ('USA', 'Canada'); - Pattern matching:
SELECT * FROM users WHERE email LIKE '%@example.com'; - Combine conditions:
SELECT * FROM products WHERE price > 100 AND stock > 0;
Tips
- Place indexed columns first in composite conditions to help the optimizer.
- Use
IS NULLandIS NOT NULLfor null checks;= NULLdoes not work as expected.
Common issues
- Using
ORwithout parentheses can produce unexpected row sets due to operator precedence. - Functions on indexed columns in
WHEREprevent index usage and cause full table scans.r