All SQL topics
SQL TOPIC

SQL ORDER BY and LIMIT: sort and take the top rows

ORDER BY sorts the result; LIMIT keeps only the first rows. Together they answer "top 5" questions.

ORDER BY sorts ascending by default; add DESC for highest first. Sort by several columns to break ties, for example ORDER BY revenue DESC, name.

Without ORDER BY, SQL does not promise any row order, even if the output looks sorted.

Worked example

What are the three most expensive products?

SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3;
Result on the sample data
nameprice
14-inch laptop1199
Mini PC549
Standing desk499

Common mistakes

  • Using LIMIT without ORDER BY and getting an arbitrary "top" list.
  • Forgetting a tie-breaker, so equal values come back in a different order each time.