CodeMIRAI
0 XP

ORDER BY and LIMIT

2 min read 6 runnable examples Quiz included

Without ORDER BY, a database returns rows in whatever order is convenient for it. To get a guaranteed order, sort explicitly.

Sorting

SQL
SELECT name, price
FROM products
ORDER BY price;

ORDER BY sorts ascending (smallest first, A to Z) by default. Add DESC for descending:

SQL
SELECT name, price
FROM products
ORDER BY price DESC;

Sorting by several columns

The second column breaks ties in the first:

SQL
SELECT name, category, price
FROM products
ORDER BY category, price DESC;

Products are grouped by category alphabetically, and within each category the most expensive comes first.

LIMIT: the top N

LIMIT keeps only the first rows of the result. Combined with ORDER BY, it answers "top N" questions:

SQL
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3;

OFFSET: skipping rows

OFFSET skips rows first, which is how pages of results work (page 2 = skip the first page):

SQL
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3 OFFSET 3;

Sorting by a calculated column

You can sort by an alias:

SQL
SELECT first_name, salary, salary / 12 AS monthly
FROM employees
ORDER BY monthly DESC
LIMIT 5;
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.