🌱BeginnerFiltering & Sorting
WHERE Clause
Filter rows in SELECT, UPDATE, and DELETE using the WHERE clause.
Overview
The WHERE clause is how you filter rows only rows where the condition evaluates to TRUE are included. WHERE works with SELECT (filtering results), UPDATE (deciding which rows to modify), and DELETE (deciding which rows to remove). A WHERE clause can contain any combination of comparisons, logical operators, functions, and subqueries.
The most important thing to remember about WHERE: it compares against TRUE only. A NULL comparison (e.g., WHERE col = NULL) never matches any row you must use IS NULL or IS NOT NULL for null checks. This "three-valued logic" (TRUE / FALSE / NULL) is a common source of bugs.
Key Points
- •WHERE col = value equality filter; returns only rows where condition is TRUE
- •NULL comparisons must use IS NULL / IS NOT NULL never = NULL
- •Combine conditions: WHERE a = 1 AND b = 2 (both must be true)
- •WHERE a = 1 OR b = 2 at least one condition must be true
- •WHERE col IN (v1, v2, v3) shorthand for multiple OR conditions
- •WHERE col BETWEEN low AND high inclusive range check
Examples
Common WHERE patterns
-- Equality and comparison
SELECT * FROM products WHERE price > 10;
SELECT * FROM orders WHERE status = 'pending';
-- Range filter
SELECT * FROM events WHERE occurred_at BETWEEN '2024-01-01' AND '2024-12-31';
-- Multiple conditions
SELECT * FROM users WHERE is_active = TRUE AND created_at > NOW() - INTERVAL '30 days';NULL handling in WHERE
-- WRONG never matches any row
SELECT * FROM users WHERE middle_name = NULL;
-- CORRECT
SELECT * FROM users WHERE middle_name IS NULL;
SELECT * FROM users WHERE middle_name IS NOT NULL;Exercises
Write SQL to solve each exercise. Your progress is saved automatically.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4