Sorting and limiting
Put rows in order with ORDER BY and take just the top few with LIMIT.
- Sort results with ORDER BY (ascending and descending)
- Sort by multiple columns
- Take the top N rows with LIMIT
Query results from a table have no guaranteed order unless you ask for one. ORDER BY
sorts them — ascending by default, or DESC for descending:
Multiple sort keys
Sort by several columns; later keys break ties in earlier ones:
Customers group by country, and within each country they're alphabetical.
Top N with LIMIT
LIMIT returns at most that many rows — combine it with ORDER BY to get "the
top few":
That's the two most expensive products. Without the ORDER BY, LIMIT would
return an arbitrary two rows — order first, then limit.
LIMIT is the standard in SQLite, PostgreSQL, and MySQL. SQL Server uses
TOP (and the standard OFFSET … FETCH) instead — exactly the kind of
difference the dialect appendices cover.
Where to go next
So far, one row in → one row out. Next, summarise many rows into totals with aggregates and grouping.