SQL ORDER BY
ORDER BY sorts the result. Without it, a database can return rows in any order, so add it whenever order matters.
Updated December 1, 2026
Syntax
SELECT columns
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
Sort descending
ASC (smallest first) is the default. DESC reverses it.
SELECT name, calories
FROM drinks
ORDER BY calories DESC;
| name | calories |
|---|---|
| Hot Chocolate | 320 |
| Mocha | 290 |
| Matcha Latte | 240 |
| Chai Latte | 230 |
| Latte | 190 |
Sort by several columns
The second column breaks ties in the first. Here, categories A–Z, then the priciest drink first within each.
SELECT category, name, price
FROM drinks
ORDER BY category, price DESC;
| category | name | price |
|---|---|---|
| coffee | Mocha | 5 |
| coffee | Cold Brew | 4.75 |
| coffee | Latte | 4.5 |
| coffee | Cappuccino | 4.25 |
| coffee | Espresso | 3 |
| other | Hot Chocolate | 4 |
| other | Lemonade | 3.5 |
| tea | Matcha Latte | 5.25 |
| tea | Chai Latte | 4.75 |
| tea | Peppermint Tea | 3.25 |
Sort by a calculated value
You can sort by an expression or by a column alias.
SELECT name, price * stock AS stock_value
FROM products
ORDER BY stock_value DESC;
| name | stock_value |
|---|---|
| Notebook (3-pack) | 4500 |
| Monitor 27" | 3735 |
| USB-C Cable | 3600 |
| Mechanical Keyboard | 3560 |
| Wireless Mouse | 3000 |
Common mistakes
- Writing
ORDER BY price, DESC. The direction goes right after its column, with no comma:ORDER BY price DESC. DESCapplies to one column only: inORDER BY category, price DESC, category still sorts ascending.- Sorting numbers stored as text: “10” sorts before “9”. Store numbers as numbers, or
CASTthem.
Practice ORDER BY interactively
Write real queries in your browser and get instant feedback in the lesson “ORDER BY” (Unit 3). New learners can start free from the first lesson.
Frequently asked questions
Can I sort by a column I don’t select?
Yes, in most cases. The exception is with DISTINCT or GROUP BY, where you can only sort by what’s in the result.
What does ORDER BY 2 mean?
Sort by the second column in the SELECT list. It works, but naming the column is clearer and safer.