Order By
By the end of this lesson you'll be able to put query results in exactly the order you want — cheapest to dearest, A to Z, newest first — break ties with a second column, sort by a calculated value, and pull the "top 3" of anything by pairing ORDER BY with LIMIT . Sorting turns a raw pile of rows into an answer.
Part of the free SQL course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn
Our Sample Table: products
Every query in this lesson runs against this same little products table — the one you met in the SELECT lesson. Notice the prices and stock levels; you'll be sorting by them in a moment.
1. ORDER BY — Ascending Is the Default
An ORDER BY clause answers "show me this data, but in order ". You add it after FROM (and after WHERE , if you have one), then name the column to sort by. By default it sorts in ascending order — smallest number first, A before Z, oldest date first.
ORDER BY is the "Sort by" dropdown on every shopping site. "Price: Low to High" is ORDER BY price ; "Price: High to Low" is ORDER BY price DESC ; "Name: A–Z" is ORDER BY product_name .
2. DESC — Flip to Descending
Add the keyword DESC after the column to reverse the sort: largest number first, or Z before A for text. (There's an ASC keyword too, but since ascending is already the default you rarely need to type it.)
Your Turn: sort cheapest first
Fill in the one blank to list every product from cheapest to most expensive. The expected result is in the comments so you can check yourself.
3. Multiple Columns — Tie-Breakers
List more than one column, separated by commas, to build a sort hierarchy . SQL sorts by the first column; the second column is only consulted when two rows tie on the first. Each column gets its own direction.
4. Sort by an Alias or an Expression
You're not limited to sorting by stored columns. You can sort by a calculated column — and the tidy way to do it is to give the calculation an alias with AS , then sort by that alias. The underlying table is untouched; the new column lives only in this result.
5. A Word on NULL Values
A NULL is a missing or unknown value — not zero, not an empty string, just "no value here". When you sort a column that contains NULLs, they get bunched together at one end, but which end depends on the database (SQLite and MySQL put them first in ascending order; PostgreSQL puts them last).
6. Top-N — ORDER BY + LIMIT
This is the combo you'll reach for constantly. Sort the rows the way you want, then add LIMIT n to keep only the first n . ORDER BY ... DESC LIMIT 3 gives you the "top 3"; switch to ASC and it's the "bottom 3" instead.
"3 most expensive products" = ORDER BY price DESC LIMIT 3 . "3 best-stocked products" = ORDER BY stock DESC LIMIT 3 . The LIMIT always comes after the ORDER BY — sort first, then trim.
Your Turn: the 3 most expensive
Two blanks this time — pick the direction keyword and the row count to return the three priciest products.
7. Where ORDER BY Fits in a Query
SQL clauses must appear in a fixed order. ORDER BY always comes after WHERE and before LIMIT :
Mentally, the database filters with WHERE , sorts the survivors with ORDER BY , and only then trims with LIMIT — which is exactly why "top 3 cheapest" works: the cheapest can't be chosen until everything is sorted.
Common Errors (and the fix)
- Forgetting DESC : ORDER BY price sorts cheapest-first because ascending is the default. If you wanted the most expensive at the top, you need ORDER BY price DESC .
- Sorting by a column you didn't select: SELECT product_name FROM products ORDER BY price is allowed and works — but the result has no price column, so the order can look random to a reader. Select the column you sort by when clarity matters.
- Text vs. numbers: sorting a number stored as text sorts it alphabetically, so "100" comes before "9" . Make sure a price column is a numeric type, not text.
- Expecting order without ORDER BY : a plain SELECT * FROM products may look sorted by id , but SQL guarantees nothing. Never rely on "natural" order — add an explicit ORDER BY .
- Putting ORDER BY before WHERE : the clauses have a strict order. It's always WHERE → ORDER BY → LIMIT .
📘 Quick Reference
Syntax
Result
Frequently Asked Questions
No. Ascending is the default, so ORDER BY price and ORDER BY price ASC are identical. Type ASC only when it makes a multi-column sort easier to read.
Q: Can I sort by a column I didn't put in SELECT ?
Yes — ORDER BY can use any column in the table, selected or not. It works, but selecting the sort column usually makes the result clearer to whoever reads it.
Q: How do I get just the "top 3" of something?
Sort the way you want and add LIMIT 3 . For the 3 most expensive: ORDER BY price DESC LIMIT 3 . For the 3 cheapest, use ASC .
Q: Why are my rows out of order when I didn't use ORDER BY ?
Because SQL never guarantees an order without one. Any apparent ordering is luck and can change. Add ORDER BY whenever order matters.
Mini-Challenge: The 3 Cheapest
Put it all together — a brief, a blank canvas, and the expected result in the comments. Write it, then copy it into a playground to confirm.
🎉 Lesson Complete
- ✅ ORDER BY col sorts results; ascending is the default
- ✅ DESC flips to descending (highest / Z→A first)
- ✅ A second sort column acts as a tie-breaker for the first
- ✅ You can sort by an alias or a calculated expression
- ✅ NULL s clump at one end; COALESCE gives you control
- ✅ ORDER BY ... LIMIT n gives you the top-N of anything
- ✅ Next: JOIN operations — combining data from multiple tables
Practice quiz
What is the default sort direction of ORDER BY?
- Descending (DESC)
- Random
- Ascending (ASC)
- Insertion order
Answer: Ascending (ASC). ORDER BY sorts ascending by default, so ORDER BY price and ORDER BY price ASC are identical.
What does the DESC keyword do?
- Sorts in descending order (highest / Z to A first)
- Removes duplicates
- Limits the rows
- Skips NULLs
Answer: Sorts in descending order (highest / Z to A first). DESC reverses the sort: largest number first, or Z before A for text.
In ORDER BY category ASC, price DESC, what is the role of price?
- It is ignored
- It is the only sort key
- It filters the rows
- It breaks ties when two rows share the same category
Answer: It breaks ties when two rows share the same category. The second column is a tie-breaker, only consulted when rows tie on the first column.
Without an ORDER BY, what does SQL guarantee about row order?
- Rows always come back sorted by id
- Nothing — order is not guaranteed
- Rows come back in insertion order
- Rows come back alphabetically
Answer: Nothing — order is not guaranteed. Without ORDER BY, SQL makes no promise about row order; it can change between runs.
Which query returns the 3 most expensive products?
- ORDER BY price DESC LIMIT 3
- ORDER BY price ASC LIMIT 3
- LIMIT 3 ORDER BY price
- ORDER BY price DESC OFFSET 3
Answer: ORDER BY price DESC LIMIT 3. Sort dearest-first with DESC, then LIMIT 3 keeps the top three.
Where must ORDER BY appear relative to WHERE and LIMIT?
- Before WHERE
- After LIMIT
- After WHERE and before LIMIT
- Anywhere in the query
Answer: After WHERE and before LIMIT. The fixed order is WHERE then ORDER BY then LIMIT: filter, sort, then trim.
Can you sort by a calculated column using its alias, e.g. ORDER BY sale_price?
- No, only stored columns can be sorted
- Yes, you can ORDER BY an alias or expression
- Only if the alias is in WHERE
- Only with DISTINCT
Answer: Yes, you can ORDER BY an alias or expression. You can sort by a calculated column, conveniently by referring to its alias.
Can you ORDER BY a column you did not include in the SELECT list?
- No, it errors
- Only the id column
- Only if you add DISTINCT
- Yes, any table column can be used to sort
Answer: Yes, any table column can be used to sort. ORDER BY can use any column in the table whether or not it is selected.
If a numeric value is stored as text, how does ORDER BY treat it?
- Numerically, so 9 before 100
- Alphabetically, so '100' before '9'
- It errors
- It ignores those rows
Answer: Alphabetically, so '100' before '9'. Text is sorted alphabetically, so '100' sorts before '9'; store numbers in a numeric type.
How do you get the 3 cheapest products instead of the 3 most expensive?
- Use ORDER BY price DESC LIMIT 3
- Use OFFSET 3
- Use ORDER BY price ASC LIMIT 3
- Use DISTINCT price
Answer: Use ORDER BY price ASC LIMIT 3. Switch the direction to ASC (cheapest first) and keep LIMIT 3.
Continue this course
- Previous: WHERE Clause & Filtering
- Next: JOIN Operations