LIMIT & OFFSET — Top-N and Paging in SQL
Cap the result, skip ahead page by page
LIMIT caps how many rows come back; OFFSET skips rows before returning — together they power “top 3 earners” lists and page-by-page results. They always ride on ORDER BY: a top-N without a sort is a random N. Dialect note: MySQL/PostgreSQL/SQLite use LIMIT…OFFSET, SQL Server uses TOP or OFFSET-FETCH.
Sort first, always
LIMIT without ORDER BY returns an arbitrary N — the sort decides which rows deserve to be first.
Cap with LIMIT
LIMIT 3 keeps at most three rows after sorting.
Skip with OFFSET
OFFSET 3 discards the first three rows — page 2 begins where page 1 ended.
Page arithmetic
Page p of size s is LIMIT s OFFSET (p−1)·s — page 3 of 5 uses OFFSET 10.
Know the dialect
SQL Server spells it TOP n or OFFSET … FETCH FIRST n ROWS ONLY; MySQL/PostgreSQL/SQLite use LIMIT…OFFSET.
1SELECT name, salary2FROM employees3ORDER BY salary DESC4LIMIT 3 OFFSET 0;
| name | salary |
|---|---|
| Cynthia | 91000 |
| Alice | 85000 |
| Farid | 73000 |
The podium: three highest-paid employees. Change OFFSET to 3 and the second-page trio appears instead. Drag the sliders in the visualization.
Top-N
The podium query — sort, then cap.
1SELECT name, salary2FROM employees3ORDER BY salary DESC4LIMIT 3;
| name | salary |
|---|---|
| Cynthia | 91000 |
| Alice | 85000 |
| Farid | 73000 |
Paging with OFFSET
Page 2 of the same sorted list.
1SELECT name, salary2FROM employees3ORDER BY salary DESC4LIMIT 3 OFFSET 3;
| name | salary |
|---|---|
| Elena | 58000 |
| Bob | 52000 |
| David | 47000 |
A short last page
The final page may hold fewer rows than the page size.
1SELECT name, salary2FROM employees3ORDER BY salary DESC4LIMIT 4 OFFSET 3;
| name | salary |
|---|---|
| Elena | 58000 |
| Bob | 52000 |
| David | 47000 |
LIMIT without ORDER BY
A bug in waiting — the N you get is arbitrary.
1SELECT name, salary FROM employees LIMIT 3;2-- which 3? undefined!
| name | salary |
|---|---|
| Alice | 85000 |
| Bob | 52000 |
| Cynthia | 91000 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.