← SQL and databases

Top results with LIMIT

Show only the first few rows.

Start this lesson

LIMIT n keeps only the first n rows of the result. Together with ORDER BY it answers "top" questions: the 3 longest books, the cheapest product, the 5 newest orders. Sort first so the right rows are at the top, then cut. OFFSET skips rows before it starts counting, which is how websites show "page 2" of results.

SELECT title, pages FROM books
ORDER BY pages DESC
LIMIT 3;

Sorts books from longest to shortest, then keeps the first 3.

LIMIT goes at the very end, after ORDER BY.

LIMIT without ORDER BY gives you some rows, but which ones is not guaranteed.