The WHERE clause is how you filter rows in a query. Without it, SELECT returns every row in the table. With WHERE, you can pick exactly the rows you want. It is like asking a specific question instead of reading the entire phone book.
Basic Comparison Operators
You can compare values using these operators:
-- Equal to
SELECT * FROM students WHERE first_name = 'Alice';
-- Not equal to
SELECT * FROM students WHERE first_name != 'Alice';
-- Greater than / Less than
SELECT * FROM students WHERE date_of_birth > '2000-01-01';
SELECT * FROM students WHERE date_of_birth < '1999-12-31';
-- Greater than or equal / Less than or equal
SELECT * FROM students WHERE id >= 10;
Combining Conditions
Use AND and OR to combine multiple conditions:
-- AND: both conditions must be true
SELECT * FROM students
WHERE date_of_birth > '2000-01-01'
AND enrollment_date > '2023-01-01';
-- OR: at least one condition must be true
SELECT * FROM students
WHERE first_name = 'Alice' OR first_name = 'Bob';
You can chain as many conditions as you need. Use parentheses to control the order of evaluation.
BETWEEN
A shorthand for range comparisons:
SELECT * FROM students
WHERE date_of_birth BETWEEN '2000-01-01' AND '2002-12-31';
This is equivalent to using >= AND <=. It works with dates, numbers, and text.
IN
Check if a value matches any value in a list:
SELECT * FROM students
WHERE first_name IN ('Alice', 'Bob', 'Charlie');
-- The opposite: NOT IN
SELECT * FROM students
WHERE first_name NOT IN ('Alice', 'Bob');
This is cleaner than writing a bunch of OR conditions.
LIKE Pattern Matching
Search for patterns in text:
-- Names starting with 'A'
SELECT * FROM students WHERE first_name LIKE 'A%';
-- Names ending with 'son'
SELECT * FROM students WHERE last_name LIKE '%son';
-- Names with 'li' anywhere
SELECT * FROM students WHERE first_name LIKE '%li%';
-- Exactly 5 characters
SELECT * FROM students WHERE first_name LIKE '_____';
The % matches any sequence of characters. The _ matches exactly
one character.
IS NULL
Check for missing values:
-- Find students without an email
SELECT * FROM students WHERE email IS NULL;
-- Find students with an email
SELECT * FROM students WHERE email IS NOT NULL;
Never use = NULL or != NULL. NULL is not a value — it represents
the absence of a value. Always use IS NULL or IS NOT NULL.
NOT
Negate any condition:
SELECT * FROM students
WHERE NOT first_name = 'Alice';
-- Same as:
SELECT * FROM students
WHERE first_name != 'Alice';