~/learn/SQL · Filtering & sorting
Filtering and sorting
WHERE narrows rows, ORDER BY arranges them, LIMIT trims them.
why this matters
Real tables have thousands of rows; you almost never want all of them. Filtering is how you answer "which customers…", "which orders…" questions.
| idINTEGER | nameTEXT | countryTEXT | signup_dateTEXT |
|---|---|---|---|
| 1 | Ada Lovelace | UK | 2023-01-14 |
| 2 | Grace Hopper | USA | 2023-02-02 |
| 3 | Alan Turing | UK | 2023-02-19 |
| 4 | Katherine Johnson | USA | 2023-03-05 |
showing 4 of 8 rows · 4 columns
WHERE keeps only the rows whose condition is true. You can combine conditions with AND / OR, and match ranges or lists with BETWEEN and IN.
Try it: Change the range so only products under 100 come back.
Text matching uses LIKE, where % stands for any run of characters. Missing values are compared with IS NULL, never with = NULL.
ORDER BY sorts the result (ASC by default, DESC for the reverse) and LIMIT cuts it down to the first N rows — together they answer 'top N' questions.
Try it: Return the three cheapest products instead.
Common gotcha
WHERE country = NULL never matches anything, not even the rows that really are empty. Comparing to NULL always gives "unknown", so use IS NULL and IS NOT NULL instead.
The order SQL runs in
FROM → WHERE → SELECT → ORDER BY → LIMIT SQL filters rows first, then picks columns, then sorts, then cuts to the top N.
Quote your text
Text values need single quotes: WHERE country = 'UK'. Without quotes SQL thinks UK is a column name.
Common gotcha
AND binds tighter than OR. Write WHERE (country = 'UK' OR country = 'USA') AND price > 100 — the brackets matter.
key takeaways
- WHERE keeps rows that match a condition.
- ORDER BY sorts; add DESC for biggest first.
- LIMIT keeps only the first N rows.
check your understanding
Which query returns the 3 most expensive products?
free practice
Build confidence with a question you can solve without Pro.