Sorting and Limiting

Lesson 7 of 20

Turn a jumbled table into a leaderboard: ORDER BY lines the rows up and LIMIT keeps only the top of the list.

The big picture

Put the rows in order, then cut

Raw scan order is random soup. ORDER BY cooks the rows into a ranking; LIMIT serves only the top slices.

ORDER BY sorts

Names a column to sort by. ASC (small to big) is the default; DESC flips it.

LIMIT trims

Keeps only the first N rows of the finished result.

Order matters

Sorting happens BEFORE the limit: LIMIT 3 returns the top 3 of the sorted list.

Top-N pattern

ORDER BY ... LIMIT is the classic leaderboard query behind games, shops and feeds.