Basic · Lesson 4 of 14

ORDER BY and LIMIT

Sort results and take the top N.

ORDER BY sorts the output

A columns list sorts by the first column, then breaks ties with the next. Use DESC for descending. ORDER BY runs after SELECT, which is why aliases are allowed here.

LIMIT cuts the rows

LIMIT returns the first N rows after sorting. "Top 3" questions are literally ORDER BY ... LIMIT 3.

Pairs with aggregate questions

Top-N-per-group and running totals also lean on ORDER BY inside window frames. Master this now and the hard questions feel familiar.

Examples

Sort then cut

The five longest titles.

SELECT title, runtime_minutes FROM content ORDER BY runtime_minutes DESC LIMIT 5;

Two sort keys

Country first, plan breaks ties.

SELECT country, plan FROM users ORDER BY country, plan;

Aliases work in ORDER BY

Ordering by a SELECT alias is allowed.

SELECT name, plan AS membership FROM users ORDER BY membership;