Hone

Lessons · SQL · LIMIT

Just some of the rows

LIMIT n returns at most n rows; ORDER BY decides which n.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Pagination, previews, top-N, sampling a query before running it on everything.

How to think about it

Which rows come first, and says who? Never LIMIT without ORDER BY when it matters which rows: without an order, 'first' is arbitrary.

Worked example

SELECT title FROM films ORDER BY year DESC LIMIT 5;
The five newest.
SELECT title FROM films ORDER BY year LIMIT 10 OFFSET 20;
Page 3 of 10 per page.

Your turn

Three cheapest products.

SELECT name FROM products ORDER BY price  3;

The trap

OFFSET on big tables gets slower with each page; keyset pagination (WHERE id > last_seen) does not.

Practise LIMIT on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.