Query data
Filter rows with WHERE
Write precise conditions with comparison, logical, range, set, pattern, and NULL operators.
A WHERE clause keeps rows where its condition is true. False and unknown conditions are both excluded.
Suppose people contains:
| name | active | age | |
|---|---|---|---|
| Ada | true | 36 | [email protected] |
| Lin | true | 15 | NULL |
| Sam | false | 42 | [email protected] |
This query returns only Ada:
SELECT name, email
FROM people
WHERE active = TRUE AND age >= 18;
SQL has three-valued logic: true, false, and unknown. A comparison with NULL normally produces unknown:
WHERE email = NULL
That condition does not find missing email addresses. Use:
WHERE email IS NULL
That returns Lin.
The same issue appears with inequality. email <> '[email protected]' returns Sam, but not Lin, because Lin’s comparison is unknown. Use email <> '[email protected]' OR email IS NULL when missing values belong in the result.
Parentheses make mixed conditions explicit:
WHERE active = TRUE
AND (country = 'Italy' OR country = 'Denmark')
Without the parentheses, operator precedence can include inactive rows from one country.
Use IN for a set of values, BETWEEN for an inclusive range, and LIKE for a pattern when those forms express the requirement clearly. They do not remove the need to reason about NULL. age BETWEEN 18 AND 65 still excludes rows where age is NULL.
String comparisons can be case-sensitive depending on your database collation. If WHERE name = 'ada' returns nothing but the row exists as Ada, check whether your database compares case-insensitively or whether you need LOWER(name).
Try this on your own: predict which three sample rows match four conditions (age >= 18, email IS NULL, email <> '[email protected]', and active = TRUE OR age >= 18). Then run the queries and compare.
Lesson completed