SELECT, WHERE, ORDER BY & LIMIT
Filter, sort and page through rows with precise conditions.
By Invicly Tech, , in SQL & PostgreSQL. About 9 minutes to read.
In short
SELECT reads rows from a table. WHERE keeps only rows that match a condition, ORDER BY sorts them and LIMIT returns just the first few. Without ORDER BY, row order is not guaranteed.
Explained simply
A table is like a spreadsheet: rows are records (one customer, one order) and columns are fields (name, price, date). SELECT is how you ask the database to show you some of those rows and columns.
A query reads almost like English. "Show me the name and price of products in the books category, cheapest first, only the first five." In SQL that becomes SELECT name, price FROM products WHERE category = 'books' ORDER BY price LIMIT 5.
Each part has one job. SELECT picks columns. FROM picks the table. WHERE throws away rows that do not match. ORDER BY sorts what is left. LIMIT cuts the list short. You can leave out any part except SELECT.
The database does not change anything when you run SELECT. It only reads. That makes SELECT the safest place to start experimenting: try a condition, look at the result, adjust, and run it again.
Press Play on a diagram to walk through it one step at a time.
- 1FROM
Pick the table to read
- 2WHERE
Keep rows where the condition is true
- 3SELECT
Compute the output columns and aliases
- 4ORDER BY
Sort the remaining rows
- 5LIMIT / OFFSET
Return only the requested slice
- ORDER BY id LIMIT 20 OFFSET 40
- Reads and throws away 40 rows
- Slower on every later page
- Can repeat rows if new data arrives
- WHERE id > 40 ORDER BY id LIMIT 20
- Jumps straight to id 41 via index
- Same speed on page 3 or 3,000
- Needs the last id from the previous page
In depth
How WHERE really decides
WHERE checks each row against a condition that must come out true. Rows where it is false, or unknown because of a NULL, are dropped.
You build conditions from small pieces. Comparisons use =, <>, <, <=, > and >=. BETWEEN 10 AND 20 includes both ends. IN ('a', 'b') matches any value in a list. LIKE 'Sam%' matches text starting with Sam, where % means any characters and _ means exactly one. ILIKE does the same but ignores upper and lower case.
AND binds tighter than OR, just like multiply before add in maths. When you mix them, add brackets so both you and the reader know what you meant.
- BETWEEN includes both ends
- LIKE is case sensitive; ILIKE is not
- % = any run of characters, _ = one character
- Brackets make AND/OR mixes safe
- Comparisons
- =, <>
- <, <=, >, >=
- Ranges and lists
- BETWEEN 10 AND 20 (both ends)
- IN ('a', 'b')
- Patterns
- LIKE 'Sam%' (case sensitive)
- ILIKE (ignores case)
- % any run, _ one character
- Logic
- AND binds tighter than OR
- Brackets make mixes safe
Sorting rules that surprise people
ORDER BY sorts ascending by default. Add DESC to reverse one column only: ORDER BY price DESC, name sorts by price high to low, then by name A to Z for ties.
NULLs count as larger than every value in Postgres, so they come last in ascending order and first in descending order. You can override this with NULLS FIRST or NULLS LAST.
If two rows tie on every sort column, their order is not fixed and can change between runs. Add a unique column such as id as the final tie-breaker whenever order matters, especially for paging.
Paging: OFFSET vs keyset
LIMIT 20 OFFSET 40 means skip 40 rows, then return 20. It is simple, but the database still has to find and throw away those 40 rows. On page 5,000 it reads 100,000 rows to show 20.
Keyset paging remembers where the last page ended. If the last row had id 1840, the next page is WHERE id > 1840 ORDER BY id LIMIT 20. With an index on id, this is just as fast on page 5,000 as on page 1. It also does not skip or repeat rows when new ones are inserted while someone is paging.
Aliases and expressions
Columns in SELECT can be calculations: price * quantity, upper(name), or a constant like 'EUR'. AS gives the result a readable name. Table aliases shorten long names: FROM products AS p lets you write p.price.
The alias is created in the SELECT step, which runs after WHERE, so WHERE cannot see it. ORDER BY runs last, so it can. If you need to filter on a calculated value, repeat the expression in WHERE or wrap the query in a subquery.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Select columns and aliases~45m
- 2Filter with WHERE, AND, OR, IN~45m
- 3Sort with ORDER BY~45m
- 4Page with LIMIT and OFFSET~45m
Key points
- List only the columns you need instead of SELECT *.
- Use AS to rename output columns: price * qty AS total.
- IN (...) is shorthand for several OR equality checks.
- Wrap mixed AND/OR conditions in parentheses to make intent explicit.
- Large OFFSET values get slow; keyset paging with WHERE id > last_id scales better.
Key terms
Tap a card to flip it. 0/5 known
Examples
SELECT id, name, price, price * 1.18 AS price_with_tax
FROM products
WHERE category IN ('books', 'games')
AND (price < 20 OR on_sale)
ORDER BY price DESC, name
LIMIT 10 OFFSET 20; -- page 3 of 10 rowsBuilding a product search step by step
A shop page wants books or games under 30 euros whose name contains "star", any case, most expensive first. Step 1: start from the table and pick columns. Step 2: add the category filter with IN. Step 3: add the price filter and wrap the OR-style part in brackets. Step 4: add ILIKE for a case-insensitive name match. Step 5: sort with a tie-breaker and limit the result.
SELECT id, name, category, price
FROM products
WHERE category IN ('books', 'games')
AND price < 30
AND name ILIKE '%star%'
ORDER BY price DESC, id
LIMIT 10;Finding this week's late orders
Support wants orders shipped later than promised in the last 7 days. Step 1: compare two columns in WHERE: shipped_at > promised_at. Step 2: limit the time window with created_at >= now() - interval '7 days'. Step 3: show the delay as a calculated column with an alias. Step 4: sort the worst delays first. Notice that ORDER BY can use the alias delay, while WHERE could not.
SELECT id, customer_id, shipped_at - promised_at AS delay
FROM orders
WHERE shipped_at > promised_at
AND created_at >= now() - interval '7 days'
ORDER BY delay DESC;Quick reference
- SELECT cols FROM t WHERE cond ORDER BY col [DESC] LIMIT n OFFSET m;
- Written order: SELECT, FROM, WHERE, ORDER BY, LIMIT. Run order: FROM, WHERE, SELECT, ORDER BY, LIMIT
- LIKE 'a%' starts with a; '%a' ends with a; '_' is one character; ILIKE ignores case
- BETWEEN a AND b includes both a and b
- Add a unique tie-breaker (id) to ORDER BY when paging
- Keyset paging: WHERE id > :last_id ORDER BY id LIMIT 20
- NULLs sort last in ASC; change with NULLS FIRST / NULLS LAST
Common mistakes
- Paging with LIMIT but no ORDER BY, so pages overlap or skip rows.
- a OR b AND c parses as a OR (b AND c) — use parentheses.
- Using a SELECT alias inside WHERE; WHERE runs before SELECT.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
From customers(id, name, country, created_at), list the names of customers from Germany or France, sorted by name.
- Exercise 2medium
Show the 5 newest customers whose email ends in @gmail.com, with a column called days_since_signup.
- Exercise 3hard
Write the query for "next page" of products sorted by price then id, given the last row of the previous page had price 19.99 and id 734.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is SELECT * bad?
- It is fine for exploring in psql. In application code, list the columns you need so the query reads less data and does not break when someone adds a column.
- Are SQL keywords case sensitive?
- No, SELECT and select are the same. Text values in quotes are case sensitive, so 'Books' and 'books' are different.
- Why does my query with double quotes around text fail?
- In Postgres, double quotes mean a column or table name and single quotes mean a text value. Write WHERE name = 'Ann', not "Ann".