No app shows a million rows at once. Search results, product lists and news feeds are split into pages of 10, 20 or 50 rows. SQL offers two ways to fetch a page. LIMIT/OFFSET is simple and lets users jump to any page number. Keyset pagination (also called seek pagination) stays fast on huge tables and does not skip or repeat rows when new data arrives. This lesson builds both and shows when to use each.
In this lesson you will learn
- Offset pagination with
LIMITandOFFSET - Calculating the offset and the number of pages
- Why offset pages can repeat or skip rows
- Keyset pagination with
WHERE id < last_id - Keyset pagination on a non-unique column, with an index
You should know ORDER BY and LIMIT and the basics of indexes.
LIMIT/OFFSET Pagination
-- 1,000 posts with ids 1..1000, newest = highest id
CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT, created TEXT);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1000)
INSERT INTO posts SELECT i, 'Post ' || i, date('2024-01-01', '+' || i || ' days') FROM n;
-- Page 3 with LIMIT/OFFSET (5 posts per page, newest first)
SELECT id, title FROM posts
ORDER BY id DESC
LIMIT 5 OFFSET 10;
-- Total pages for a page size of 5
SELECT COUNT(*) AS posts, (COUNT(*) + 4) / 5 AS pages FROM posts;
-- A new post arrives while the user is reading page 1...
INSERT INTO posts VALUES (1001, 'Post 1001', '2026-09-28');
-- ...so page 2 now repeats the last post of page 1 (id 996)
SELECT id, title FROM posts ORDER BY id DESC LIMIT 5 OFFSET 5;
Output
+-----+----------+
| id | title |
+-----+----------+
| 990 | Post 990 |
| 989 | Post 989 |
| 988 | Post 988 |
| 987 | Post 987 |
| 986 | Post 986 |
+-----+----------+
(5 rows)
+-------+-------+
| posts | pages |
+-------+-------+
| 1000 | 200 |
+-------+-------+
(1 row)
+-----+----------+
| id | title |
+-----+----------+
| 996 | Post 996 |
| 995 | Post 995 |
| 994 | Post 994 |
| 993 | Post 993 |
| 992 | Post 992 |
+-----+----------+
(5 rows)
- The recursive CTE creates 1,000 test posts, one per day, so there is plenty of data to page through.
- For page p with n rows per page, the offset is
(p − 1) × n. Page 3 with 5 rows per page skips 10 rows and shows posts 990 to 986. (COUNT(*) + 4) / 5is integer division rounded up, giving 200 pages. In general use(total + n − 1) / n.- The problem: a user reads page 1 (posts 1000 to 996), then a new post 1001 is added. Every row shifts down by one, so page 2 begins with post 996 again. Deleted rows cause the opposite problem: a row is skipped.
- Offset also gets slower on deep pages. To return page 10,000 the database must still read and throw away all the earlier rows.
Keyset Pagination
CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT, created TEXT);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1000)
INSERT INTO posts SELECT i, 'Post ' || i, date('2024-01-01', '+' || i || ' days') FROM n;
-- Keyset (seek) pagination: page 1
SELECT id, title FROM posts ORDER BY id DESC LIMIT 5;
-- The app remembers the last id shown (996) and asks for rows after it
INSERT INTO posts VALUES (1001, 'Post 1001', '2026-09-28');
SELECT id, title FROM posts
WHERE id < 996
ORDER BY id DESC
LIMIT 5;
-- Sorting by a non-unique column: add the id as a tie-breaker
CREATE INDEX ix_posts_created_id ON posts (created, id);
SELECT id, created FROM posts
WHERE (created, id) < ('2025-06-01', 517)
ORDER BY created DESC, id DESC
LIMIT 3;
EXPLAIN QUERY PLAN
SELECT id, created FROM posts
WHERE (created, id) < ('2025-06-01', 517)
ORDER BY created DESC, id DESC
LIMIT 3;
Output
+------+-----------+
| id | title |
+------+-----------+
| 1000 | Post 1000 |
| 999 | Post 999 |
| 998 | Post 998 |
| 997 | Post 997 |
| 996 | Post 996 |
+------+-----------+
(5 rows)
+-----+----------+
| id | title |
+-----+----------+
| 995 | Post 995 |
| 994 | Post 994 |
| 993 | Post 993 |
| 992 | Post 992 |
| 991 | Post 991 |
+-----+----------+
(5 rows)
+-----+------------+
| id | created |
+-----+------------+
| 516 | 2025-05-31 |
| 515 | 2025-05-30 |
| 514 | 2025-05-29 |
+-----+------------+
(3 rows)
+-------------------------------------------------------------------+
| detail |
+-------------------------------------------------------------------+
| SEARCH posts USING COVERING INDEX ix_posts_created_id (created<?) |
+-------------------------------------------------------------------+
(1 row)
- Instead of counting rows to skip, keyset pagination remembers the last key shown (id 996) and asks for rows after it:
WHERE id < 996 ORDER BY id DESC LIMIT 5. - Post 1001 arrived between the two requests, but page 2 still starts correctly at 995. New and deleted rows cannot shift the pages.
- Because the
WHEREcondition uses the index onid, the database jumps straight to the right place. Page 10,000 is as fast as page 2. - When sorting by a column that can repeat, such as
created, add a unique column as a tie-breaker. The row-value comparison(created, id) < ('2025-06-01', 517)means “earlier date, or the same date with a smaller id”. EXPLAIN QUERY PLANshows the query reads the composite indexix_posts_created_iddirectly (SEARCH … USING COVERING INDEX) instead of scanning the table.
Offset vs Keyset
| LIMIT/OFFSET | Keyset | |
|---|---|---|
| Jump to page 57 | Yes | No, only next/previous |
| Speed on deep pages | Gets slower | Stays fast |
| New or deleted rows | Can repeat or skip rows | Stable |
| Complexity | Very simple | Needs a unique, indexed sort key |
| Typical use | Admin tables, small result sets | Feeds, infinite scroll, APIs, exports |
SQL Server and Oracle write offset pagination as OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY. Row-value comparisons work in PostgreSQL, MySQL and SQLite; elsewhere write created < :d OR (created = :d AND id < :id).
Common Mistakes
- Paging without
ORDER BY. Without it, the order of rows is not guaranteed, so pages can overlap. - Ordering by a non-unique column only, so rows with equal values can jump between pages. Add the id as a tie-breaker.
- Running
COUNT(*)on a huge table for every page request. Cache the total, or show “next” without a page count. - Building the query by concatenating user input for the page number. Use parameters.
Practice Exercises
Exercise 1. Write the offset query for page 7 with 20 rows per page, oldest posts first.
Show answer
SELECT id, title FROM posts
ORDER BY id
LIMIT 20 OFFSET 120;
The offset is (7 − 1) × 20 = 120.
Exercise 2. With keyset pagination, newest first, the current page shows posts 416 to 412. Fetch the previous page of 5 posts.
Show answer
-- :first_id = 416, the first id on the current page
SELECT * FROM (
SELECT id, title FROM posts
WHERE id > :first_id
ORDER BY id ASC
LIMIT 5
) AS p
ORDER BY id DESC;
Going backwards starts from the first id of the current page. The inner query fetches the 5 posts just above 416 (417 to 421) in ascending order, and the outer query flips them back to newest first: 421 to 417.
Frequently Asked Questions
What is cursor-based pagination in APIs?
It is keyset pagination with the last key encoded in an opaque “cursor” string. The client sends the cursor back to get the next page, without knowing which columns are used.
How can I show page numbers with keyset pagination?
You cannot jump directly to page n, but you can show “Page 3 of about 200” by counting the total separately. Many sites combine both methods: offset for the first few pages and keyset for deep scrolling.
Summary
- Offset:
LIMIT n OFFSET (p − 1) × n; simple, allows page jumps. - Offset pages slow down when deep and shift when rows change.
- Keyset:
WHERE key < last_key ORDER BY key LIMIT n; fast and stable. - Always use a unique sort key and an index that matches it.
