~/learn/SQL · Filtering & sorting

Filtering and sorting

WHERE narrows rows, ORDER BY arranges them, LIMIT trims them.

7 min readlesson 2 of 18whereorder bylimitnull

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.

idINTEGERnameTEXTcountryTEXTsignup_dateTEXT
1Ada LovelaceUK2023-01-14
2Grace HopperUSA2023-02-02
3Alan TuringUK2023-02-19
4Katherine JohnsonUSA2023-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.

sql · editable
loading editor…

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.

sql · editable
loading editor…

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.

sql · editable
loading editor…

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.