SQL ORDER BY
Without ORDER BY, a database may return rows in any order, and the order can change between runs. Whenever order matters, say so explicitly.
ORDER BY sorts ascending (ASC) by default. Add DESC for descending. You can sort by several columns; later columns break ties in earlier ones.
Syntax
SELECT columns FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
Examples
1. Cheapest first
SELECT name, price FROM products ORDER BY price;
Ascending is the default.
2. Two sort keys
SELECT category, name, price FROM products ORDER BY category, price DESC;
By category, then most expensive first within each category.
Common mistakes
- Assuming rows come back in insertion order. They don't, unless you ORDER BY.
- Sorting numbers stored as text: '100' sorts before '20'.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
Return category, name and price of all products, sorted by category A to Z, then by price highest first within each category.
FAQ
Where do NULLs go when sorting?
In PostgreSQL, NULLs come last in ascending order and first in descending order. Change this with NULLS FIRST or NULLS LAST.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.