SQL ORDER BY and LIMIT: sort and take the top rows
Rows have no order of their own. ORDER BY sorts them, LIMIT keeps the first few.
SQL skills · One table
What you will learn
Without ORDER BY the database may return rows in any order, and that order can change. If the order matters, say it.
You will sort up and down, sort by two columns and build top lists.
The basics
Rows in a table have no order of their own. If the order matters, say it with ORDER BY.
SELECT customer, amount
FROM invoices
ORDER BY amount DESCORDER BY sorts from low to high by default (A to Z, oldest date first). DESC flips it: high to low, newest first.
Top N
SELECT customer, amount
FROM invoices
ORDER BY amount DESC
LIMIT 3LIMIT keeps the first rows of the sorted result and goes at the very end. Without ORDER BY, LIMIT gives you any rows, not the top ones.
Two sort columns
ORDER BY region, amount DESCThe second column sorts rows inside each group of the first. DESC applies only to the column right before it.
Other databases
SQLite, PostgreSQL, MySQL and Snowflake use LIMIT. SQL Server writes SELECT TOP 3. Oracle writes FETCH FIRST 3 ROWS ONLY at the end.
Worked examples
Example 1
The three largest deals.
SELECT account, amount
FROM deals
ORDER BY amount DESC
LIMIT 3Sort first, then cut. LIMIT goes at the very end.
Example 2
Employees by department, and inside each department the highest salary first.
SELECT department, full_name, salary
FROM employees
ORDER BY department, salary DESCDESC applies only to the column right before it.
Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.
Try a taskCommon mistakes
- Using LIMIT without ORDER BY and expecting the top rows.
- Writing DESC once and expecting it to apply to every sort column.
- Putting ORDER BY before WHERE. The order is SELECT, FROM, WHERE, ORDER BY, LIMIT.
Where you will use it at work
- Sales: the top five accounts by deal value.
- Operations: the latest shipments first.
- Support: the slowest answered tickets.
Questions people ask
Is ASC needed?
No. Low to high is the default. ASC only makes it explicit.
How do I get the top rows in SQL Server or Oracle?
SQL Server writes SELECT TOP 3. Oracle writes FETCH FIRST 3 ROWS ONLY after ORDER BY. The dialect tracks cover both.
Where do NULL values go when sorting?
It depends on the database: some put them first, some last. PostgreSQL and Oracle let you say NULLS LAST.
Ready to write it yourself?
Practice Sort with ORDER BY, cut with LIMIT