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;
Result on the SQL Café sample data (10 rows, first 5 shown)
namecalories
Hot Chocolate320
Mocha290
Matcha Latte240
Chai Latte230
Latte190

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;
Result on the SQL Café sample data (10 rows)
categorynameprice
coffeeMocha5
coffeeCold Brew4.75
coffeeLatte4.5
coffeeCappuccino4.25
coffeeEspresso3
otherHot Chocolate4
otherLemonade3.5
teaMatcha Latte5.25
teaChai Latte4.75
teaPeppermint Tea3.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;
Result on the Desk & Co. (online store) sample data (10 rows, first 5 shown)
namestock_value
Notebook (3-pack)4500
Monitor 27"3735
USB-C Cable3600
Mechanical Keyboard3560
Wireless Mouse3000

Common mistakes

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.

Related SQL tutorials