Filtering & Sorting
Pick the rows you want with WHERE, and set the order they come back in with ORDER BY.
What is it?
SELECT * FROM orders returns every order. Usually you want something narrower: orders from this month, the five most expensive, users whose name starts with "A."
WHEREkeeps only the rows that match a condition.ORDER BYsorts the results by any column, ascending or descending.
They're often used together: filter to the rows you care about, then sort them.
Explain like I'm 10
WHERE is sorting a laundry basket down to just the socks. ORDER BY is lining those socks up from smallest to biggest. You can do either alone, or both.
Examples
Filtering with WHERE
SELECT name, total_cents
FROM orders
WHERE total_cents > 5000;Returns only orders over 5000 cents ($50). Every other row is left out.
Combining filtering, sorting, and limiting
SELECT name, total_cents
FROM orders
WHERE total_cents > 5000
ORDER BY total_cents DESC
LIMIT 3;Finds orders over $50, sorts them from highest total to lowest (DESC means descending), then keeps the top 3.
How it works
The database checks the WHERE condition against each row and keeps the rows where it's true. You can combine conditions with AND and OR. ORDER BY sorts the remaining rows by one or more columns, ASC (ascending, the default) or DESC (descending). LIMIT caps how many sorted rows come back.
Without an index (a topic of its own), the database usually has to check every row against WHERE. Indexes exist to speed up exactly that lookup.
Why does it exist?
Apps rarely want "everything, in whatever order it's stored." Filtering and sorting let the database do that work, instead of your code fetching every row and filtering and sorting in memory, which is slower and more code.
When to use it
Use WHERE whenever you want only some rows. Use ORDER BY whenever order matters: recent-first feeds, cheapest-first product lists, alphabetical names.
When not to use it
If you need every row and order doesn't matter (say, a batch job that processes rows in any order), skip WHERE and ORDER BY to save the database work.
Common mistakes
Forgetting ORDER BY defaults to ascending, which looks 'backwards' for dates when you want newest first.
Fetching all rows and filtering in app code instead of using WHERE. Much slower on large tables.
Assuming rows come back in some order automatically. Without ORDER BY, no order is guaranteed.
Practice exercises
- Easy:
Write a query that selects all products with a price less than 20 from a products table.
- Medium:
Write a query that returns the 5 most recently created rows from an orders table with a created_at column.
- Hard:
Using WHERE and ORDER BY, find the 3 cheapest in-stock products in a products table with price and in_stock columns.
Interview questions
What does the WHERE clause do?
It filters which rows a query applies to, keeping only rows where the given condition evaluates to true.
What does ORDER BY control, and what's the default direction?
It controls the order results are returned in, by one or more columns; the default direction is ascending (ASC) unless DESC is specified.
If you don't use ORDER BY, is the order of returned rows guaranteed?
No — without an explicit ORDER BY, the database doesn't guarantee any particular row order.
What does `WHERE age = NULL` actually do, and why doesn't it match rows where age is NULL?
It never matches anything. Comparing to NULL with = (or any comparison) gives unknown, not true or false, because you can't know whether an unknown value equals something. Use WHERE age IS NULL instead.
What are the three possible outcomes of evaluating a WHERE condition?
True, false, and unknown. Unknown usually comes from comparisons involving NULL. WHERE keeps only true rows; false and unknown rows are excluded.
Given a table where some rows have age as NULL, what does `WHERE age > 20` return for those rows, and what about `WHERE NOT (age > 20)`?
Neither returns them. age > 20 is unknown for a NULL age, and NOT unknown is still unknown. Both queries silently drop those rows.
Why is `WHERE column <> 5` on a column containing some NULL values likely to exclude more rows than expected?
A NULL compared with anything gives unknown, so NULL rows fail <> just as they fail =. They're dropped from both the equals-5 and not-equals-5 results, even though 'not equals' seems like it should include them.
What's a dangerous trap with `WHERE column NOT IN (list)` if that list can contain a NULL value?
If any item in the list is NULL, NOT IN can match zero rows for the whole query. NOT IN is a chain of <> checks joined by AND, and the NULL comparison makes the whole chain unknown, so every row is excluded.
Does AND bind more tightly than OR in a WHERE clause, and why does that matter?
Yes. Without parentheses AND runs first, so WHERE a = 1 OR b = 2 AND c = 3 means WHERE a = 1 OR (b = 2 AND c = 3), not WHERE (a = 1 OR b = 2) AND c = 3. Write explicit parentheses to avoid subtly wrong filters.
Is the range in `WHERE price BETWEEN 10 AND 20` inclusive or exclusive of 10 and 20?
Inclusive on both ends. BETWEEN equals price >= 10 AND price <= 20, so prices of exactly 10 or 20 are included.
What do `%` and `_` mean inside a LIKE pattern?
% matches zero or more characters; _ matches exactly one. So LIKE 'A%' matches anything starting with A, and LIKE 'A_' matches exactly two characters starting with A.
Is LIKE guaranteed to be case-sensitive?
No. It depends on the database and sometimes the column's collation. PostgreSQL's LIKE is case-sensitive by default (ILIKE is the case-insensitive version), while some other databases are case-insensitive by default. Don't assume it's the same everywhere.
When ordering by two columns, like `ORDER BY last_name ASC, age DESC`, how does the second column affect the sort?
Rows sort by last_name ascending first. age descending only breaks ties between rows with the same last_name. The second column never overrides the first.
Given the rows Kenji/34, Amara/29, and Amara/41, what order does `ORDER BY name ASC, age DESC` return them in?
Amara/41, Amara/29, Kenji/34. Names sort alphabetically first; the two Amaras tie, so age DESC puts the older one first.
Can each column listed in an ORDER BY clause have its own independent ASC/DESC direction?
Yes, direction is per column. ORDER BY total_cents DESC, created_at ASC sorts by highest total first, then by oldest created_at to break ties.
What does `LIMIT 5` do to a query's results?
It returns at most 5 rows and drops the rest.
What does `OFFSET 10` do when combined with `LIMIT 5`?
It skips the first 10 sorted rows and returns up to the next 5. This is the classic way to fetch a later page.
Why is it risky to use LIMIT/OFFSET for pagination without an ORDER BY clause?
Without ORDER BY, row order isn't guaranteed between queries, so pages aren't consistent. A row could show up on several pages or never, especially if rows are inserted or deleted between requests.
What happens if OFFSET is larger than the total number of matching rows?
The query returns zero rows. It's not an error; there's just nothing left after skipping.
In terms of logical order of evaluation, does WHERE run before or after ORDER BY?
WHERE runs first and filters rows. ORDER BY sorts what's left. Then LIMIT, if present, cuts the sorted list: filter, sort, cap.
Where do NULL values end up when sorting a column with ORDER BY — always first, or always last?
Neither; it depends on the database. Some put NULLs first in ascending order, others last. If position matters, check the default or set it explicitly with NULLS FIRST or NULLS LAST, which many databases support.
Write a query that finds the 3 cheapest in-stock products from a products table with price and in_stock columns.
SELECT * FROM products WHERE in_stock = true ORDER BY price ASC LIMIT 3;: keep in-stock products, sort cheapest first, take the first three.
A query with `WHERE total_cents > 5000 ORDER BY total_cents DESC LIMIT 3` returns only 1 row. Is that a bug?
Not necessarily. LIMIT only sets a maximum. If WHERE matched just 1 row, that's all there is to return.
How would you get the rows ranked 2nd and 3rd by price, skipping the single cheapest, using LIMIT and OFFSET?
ORDER BY price ASC LIMIT 2 OFFSET 1: sort cheapest first, skip one row, take the next two.
Why does filtering with WHERE inside the database scale better than fetching every row and filtering in application code?
The database can use indexes to jump to matching rows and never sends non-matching rows over the network. Filtering in app code means fetching, sending, and discarding every non-matching row, which wastes more database and network work as the table grows.
Without any index, how does the database evaluate a condition like `WHERE total_cents > 5000`?
Usually with a full table scan, checking every row one by one, since nothing tells it which rows might match. Indexes exist to avoid this.
What's the difference between what WHERE excludes and what LIMIT excludes?
WHERE drops rows that fail a condition, based on each row's content. LIMIT drops rows based only on their position in the filtered, sorted results, just to cap the count.
A developer expects `ORDER BY created_at DESC LIMIT 5 OFFSET 5` to always return a stable 'page 2' that never overlaps page 1, even as new orders keep being inserted. What can go wrong?
If new rows arrive between requests, existing rows shift down in the DESC order. The same row can then show up on both pages, or a row can be skipped. LIMIT/OFFSET works by position, not a stable per-row marker, so it isn't safe against concurrent inserts or deletes.