WHERE
WHERE decides which rows are eligible for everything that comes after.
If a filter is wrong, every downstream number is wrong, even when the SQL parses cleanly. That is why getting WHERE right matters more than the rest of the query combined.
Syntax #
WHERE goes right after FROM. The condition must evaluate to true for a row to be kept.
SELECT id, status, total
FROM orders
WHERE status = 'paid';Comparison Operators #
The condition in WHERE is almost always a comparison:
| Operator | Meaning |
|---|---|
= | Equal |
<> or != | Not equal |
<, <= | Less than / at most |
>, >= | Greater than / at least |
String equality is case-sensitive in most SQL dialects. status = 'Paid' and status = 'paid' are different filters. For pattern-based text matching, see LIKE later in this section.
WHERE col = NULL returns zero rows, even for rows where col really is NULL.NULL is not a value you can compare with =. Use IS NULL / IS NOT NULL instead. This is the single most common filtering mistake in SQL. Full treatment in NULL handling.
Try It #
Run the query, then change the filter and rerun.
Practice #
Return id, status, and total for orders that are paid and have a total strictly greater than 100. No ordering requirement.
Mistakes to Watch For #
- Using
= NULLinstead ofIS NULL. - Wrong case or stray whitespace in string comparisons (
'Paid '≠'paid'). - Trying to reuse a
SELECTalias inWHERE; aliases don't exist yet at filter time. - Placing an aggregate filter like
COUNT(*) > 5inWHERE. Those belong inHAVING(covered in the Aggregation section).
Knowledge check #
3 questions
When does
WHERErun, relative toGROUP BY?WHERE col = NULLreturns which rows?You want every row where
statusis not'cancelled', including rows wherestatusisNULL. What works?
Next Step #
Continue to AND / OR / NOT to combine multiple conditions in a single filter.