beginner
Filtering Rows with WHERE
Use the WHERE clause and comparison operators to filter which rows a query returns.
5 min read
Explanation
SELECT decides which columns to return. WHERE decides which rows to
return. Without a WHERE clause, a query returns every row in the table.
With one, only rows that match your condition are included.
Consider the movies table:
| id | title | genre | release_year | director | budget_millions |
|---|---|---|---|---|---|
| 1 | The Signal | Drama | 2015 | A. Reyes | 12 |
| 2 | Skyward | Sci-Fi | 2021 | A. Reyes | 180 |
| 3 | Quiet Town | Drama | 2019 | M. Okafor | 8 |
If you only want movies released after 2018, WHERE release_year > 2018
filters out everything else and leaves you with just the rows that match.
WHERE runs before your columns are shown
Think of WHERE as a filter applied to the table first — SQL checks the condition against every row, keeps the ones that match, and only then returns the columns you asked for in SELECT.
Syntax
SELECT column1, column2
FROM table_name
WHERE condition;Common comparison operators you can use in a condition:
| Operator | Meaning |
|---|---|
= | equal to |
!= or <> | not equal to |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
You can combine multiple conditions with AND (both must be true) or OR
(at least one must be true) — we'll go deeper on combining conditions in a
later lesson, but it's worth knowing they exist:
SELECT title FROM movies WHERE genre = 'Drama' AND release_year > 2018;Interactive Example
Loading database engine...
Loading database engine...
Common Mistakes
- Forgetting quotes around text values.
WHERE genre = Dramawill error or behave unexpectedly — it needs to beWHERE genre = 'Drama'. - Using
=for "not equal." Remember it's!=or<>, not=!or a single<. - Assuming WHERE can filter on a column that isn't in the table. The
column you filter on doesn't have to appear in your
SELECTlist, but it does have to exist in the table you're querying.
Best Practices
- Filter on the smallest, most specific condition you can — it makes intent clear to anyone reading the query later.
- Double-check whether a column holds text, numbers, or dates before writing a comparison, since text comparisons need quotes and dates often need a specific format.
- When a query returns unexpected results, comment out or simplify the
WHEREclause first — it's the most common source of "wrong" results.
Practice Question
Using either playground above, write a query against the movies table
that returns the title and budget_millions of every movie with a budget
under 15 million dollars.
Summary
WHERE filters rows based on a condition, using comparison operators like
=, !=, >, <, >=, and <=. You can combine simple conditions with
AND or OR, though combining several conditions well is a topic we'll
cover in more depth soon.