Code of the Day
BeginnerQuerying basics

Sorting and limiting

Put rows in order with ORDER BY and take just the top few with LIMIT.

SQLBeginner6 min read
Recommended first
By the end of this lesson you will be able to:
  • Sort results with ORDER BY (ascending and descending)
  • Sort by multiple columns
  • Take the top N rows with LIMIT

Query results from a have no guaranteed order unless you ask for one. ORDER BY sorts them — ascending by default, or DESC for descending:

SQL — editable, runs in your browser

Multiple sort keys

Sort by several columns; later keys break ties in earlier ones:

SQL — editable, runs in your browser

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":

SQL — editable, runs in your browser

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.

Finished reading? Mark it complete to track your progress.

On this page