Pagination

Updated · 8 min read
hardPostgreSQL 18sqlpaginationoffsetkeyset-paginationperformanceinterview

Pagination in SQL is returning a long result one page at a time, such as 10 payments per screen. It is used in every list, report and API that can't show everything at once. The obvious way, LIMIT 10 OFFSET 15000, works but gets slower page by page, because the database still reads and throws away every row before the page. Keyset pagination asks for "the next 10 after the last one I saw" instead, and stays fast on any page. In this lesson, we will compare the two with real plans, and learn the stable sort order both depend on.

In One Minute

  • ORDER BY ... LIMIT n OFFSET m skips m rows, but still reads them: page 1,501 reads 15,010 rows.
  • Keyset pagination remembers the last row's key: WHERE payment_id > 15000 ORDER BY payment_id LIMIT 10.
  • Keyset reads only the page's rows, on any page, if an index matches the sort.
  • Both need a stable, unique sort order; add the primary key as a tie-breaker.
  • Keyset can't jump to "page 1,500" directly; it moves forward (or backward) from a known row.

OFFSET Pagination

SQL
SELECT ... FROM table ORDER BY key LIMIT page_size OFFSET (page_number - 1) * page_size;

The examples use the generated big_payments table (20,000 rows). Page 1,501, ten rows per page:

SQL▶ Try it
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
SELECT payment_id, paid_on, amount_usd
FROM big_payments
ORDER BY payment_id
LIMIT 10 OFFSET 15000;
Output
CREATE TABLE
 
INSERT 0 20000
 
ANALYZE
 
                                       QUERY PLAN
-----------------------------------------------------------------------------------------
 Limit (actual rows=10.00 loops=1)
   Buffers: shared hit=139
   ->  Index Scan using big_payments_pkey on big_payments (actual rows=15010.00 loops=1)
         Index Searches: 1
         Buffers: shared hit=139
 Planning:
   Buffers: shared hit=27
(7 rows)

Explanation: The index scan produced actual rows=15010: it read 15,000 rows just to skip them, then returned 10, touching 139 pages. Page 2 would read 20 rows; the last page reads all 20,000. The deeper the page, the slower it gets.

Keyset (Seek) Pagination

Keyset pagination starts each page right after the last row of the previous one, using a WHERE on the sort key:

SQL▶ Try it
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
ANALYZE big_payments;
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS ON)
SELECT payment_id, paid_on, amount_usd
FROM big_payments
WHERE payment_id > 15000
ORDER BY payment_id
LIMIT 10;
Output
CREATE TABLE
 
INSERT 0 20000
 
ANALYZE
 
                                      QUERY PLAN
--------------------------------------------------------------------------------------
 Limit (actual rows=10.00 loops=1)
   Buffers: shared hit=4
   ->  Index Scan using big_payments_pkey on big_payments (actual rows=10.00 loops=1)
         Index Cond: (payment_id > 15000)
         Index Searches: 1
         Buffers: shared hit=4
 Planning:
   Buffers: shared hit=30
(8 rows)

Explanation: The index jumps straight to payment_id > 15000 and reads exactly 10 rows: 4 pages instead of 139. It costs the same on page 2 or page 1,501. The program remembers the last payment_id it showed and sends it with the "next page" request.

OFFSET 15000 reads 15,010 rows (139 pages); WHERE payment_id > 15000 reads 10 rows (4 pages)

Stable Sort Keys

Pagination needs an order where every row has one fixed position. Sorting by paid_on alone isn't enough: 27 payments share each date, and their order among themselves can change between queries, so a row might appear on two pages or on none. Add the primary key as a tie-breaker:

SQL▶ Try it
CREATE TABLE big_payments (payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, paid_on DATE NOT NULL, amount_usd NUMERIC(8,2) NOT NULL, method TEXT);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method) SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400), (ARRAY['card', 'check', 'cash'])[1 + g % 3] FROM generate_series(1, 20000) AS g;
 
SELECT payment_id, paid_on, amount_usd
FROM big_payments
ORDER BY paid_on, payment_id
LIMIT 3;
 
SELECT payment_id, paid_on, amount_usd
FROM big_payments
WHERE (paid_on, payment_id) > ('2024-01-01', 2190)
ORDER BY paid_on, payment_id
LIMIT 3;
Output
CREATE TABLE
 
INSERT 0 20000
 
 payment_id |  paid_on   | amount_usd
------------+------------+------------
        730 | 2024-01-01 |     430.00
       1460 | 2024-01-01 |     360.00
       2190 | 2024-01-01 |     290.00
(3 rows)
 
 payment_id |  paid_on   | amount_usd
------------+------------+------------
       2920 | 2024-01-01 |     220.00
       3650 | 2024-01-01 |     150.00
       4380 | 2024-01-01 |     480.00
(3 rows)

Explanation: The first query is page 1, ending at (2024-01-01, 2190). The second continues with a row comparison, (paid_on, payment_id) > ('2024-01-01', 2190), meaning "a later date, or the same date with a larger id". An index on (paid_on, payment_id) lets PostgreSQL seek straight to that point.

Sorted by paid_on alone, tied rows have no fixed order; adding payment_id gives every row one place
OFFSETKeyset
Cost of page NGrows with NConstant
Jump to page 500YesNo (move from a known row)
Rows inserted while pagingCan shift rows to the next page (duplicates or gaps)Stable
NeedsORDER BY with a tie-breakerAn index on the sort key, plus a tie-breaker

MySQL and PostgreSQL use LIMIT ... OFFSET; SQL Server and Oracle use OFFSET ... ROWS FETCH NEXT ... ROWS ONLY, as Limiting Rows showed. Keyset pagination works the same way in all of them.

OFFSET Grows; Keyset Stays Flat

Common Mistakes

Deep OFFSET pages on big tables. Each page reads every row before it. Use keyset pagination.

Sorting by a non-unique column. Rows with equal values can repeat or vanish between pages. Add the primary key.

Keyset without a matching index. Without one, the WHERE still scans. Index the sort columns.

Counting all rows for every page. count(*) on a big table can cost more than the page itself; show "next" instead of "page 1 of 2,000" when you can.

Interview Corner

Why is OFFSET pagination slow for deep pages?

The database must read and discard all the skipped rows, so the work grows with the offset.

What is keyset pagination?

Fetching the next page with a WHERE on the sort key after the last row seen, such as WHERE id > :last_id ORDER BY id LIMIT 10, which an index can satisfy in constant time.

Why does pagination need a unique sort order?

If rows tie on the sort key, their relative order isn't guaranteed, so rows can appear on two pages or be skipped. A unique tie-breaker gives each row one position.

Practice

Challenge: Using keyset pagination on the Fee Tracker's own payments, ordered by paid_on, payment_id, show the page of 3 that comes after payment 6 (paid 2025-11-14).

Show solution
SQL▶ Try it
SELECT payment_id, paid_on, amount_usd
FROM payments
WHERE (paid_on, payment_id) > ('2025-11-14', 6)
ORDER BY paid_on, payment_id
LIMIT 3;
Output
 payment_id |  paid_on   | amount_usd
------------+------------+------------
          3 | 2025-12-03 |     250.00
          7 | 2025-12-19 |     225.00
          4 | 2025-12-29 |     550.00
(3 rows)

The next three payments after November 14, in date order: payments 3, 7 and 4. The same query works whatever page you're on.

Quick check: Pagination

3 questions
1LIMIT 10 OFFSET 15000: how many rows does the database read?
2What does keyset pagination remember between pages?
3Why add payment_id to ORDER BY paid_on?

Key Takeaways

You want toWrite
Page by number (small tables)ORDER BY id LIMIT 10 OFFSET 20
Next page, fastWHERE id > :last_id ORDER BY id LIMIT 10
Next page by dateWHERE (paid_on, id) > (:last_date, :last_id) ORDER BY paid_on, id LIMIT 10

Was this tutorial helpful?

Lesson 83 of 115