Skip to content

Pagination: Offset vs Keyset ​

"The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient." — PostgreSQL 19 Documentation, §7.6 LIMIT and OFFSET

Summary: OFFSET n makes the database produce and discard n rows, and a position-based page moves when rows are inserted; keyset (seek) pagination remembers the last row's sort key and asks for rows after it, so every page costs the same. Focus: the cost and drift of offset, row-value comparison and index support, composite cursors with tie-breakers, descending and mixed order, NULLs, signed and versioned cursors, counts, jumping to page N, replicas, filters and joins, and the real API shapes (Relay, Stripe, Slack, Link headers). Learning goal: choose offset, keyset or a hybrid for a given screen or API, write the exact SQL for it on PostgreSQL and MySQL, and read an EXPLAIN to prove which one you have.

This page is the complete reference for paginating query results. It covers LIMIT/OFFSET, keyset pagination (the seek method), cursors that survive production (signed, versioned, expiring), counting without a full scan, the hybrid that gives page numbers back, the MySQL deferred join, how Laravel's paginate, simplePaginate and cursorPaginate really work, and how MongoDB, Elasticsearch and DynamoDB solve the same problem. Streaming a whole result set instead of paging it is a sibling topic: see Cursors & Streaming Results. Index design is in Indexing, reading plans in Query Planning, and ORM habits that create N+1 and offset traps in ORM Pitfalls.

Page map ​

If you are looking forGo to
A table you can memorise in one minuteEverything in one minute
Why pages exist and what goes wrongWhy pagination is hard
Where the vocabulary and the SQL standard text come fromWhere it comes from
Why OFFSET 900000 is slow and unstableOFFSET and LIMIT
The seek method, row values, tie-breakersKeyset, Row values, Tie-breakers
DESC, mixed directions, NULLsDescending and mixed order, NULLs
Cursor encoding, signing, expiry, versioningOpaque cursors, Expiry and versioning
"Page 3 of 240", estimated counts, cachingTotal counts
Infinite scroll, numbered pages, jump to page N, hybridsScroll vs pages, Hybrid
Filters, joins, replicasFilters and joins, Replicas
MySQL LIMIT, filesort, late row lookup, deferred joinMySQL
Per-database and per-API behaviourPer-engine behaviour
Laravel paginate, simplePaginate, cursorPaginate, chunkByIdLaravel internals
SQL + Go + Laravel recipesSolving the classic problems
Which method for which screenChoosing
Monolith to distributedIn architecture
Reproduce everything on 1M rowsLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The two families.

Offset (page number)Keyset (seek, cursor)
Question the query asks"Skip n rows, then give me 50""Give me 50 rows after this key"
SQLORDER BY created_at DESC, id DESC LIMIT 50 OFFSET 900000WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 50
Cost of page NGrows with N: N x 50 rows produced and discardedConstant: one index seek plus 50 entries
Stable under inserts and deletesNo: rows shift, so duplicates and gapsYes: the boundary is a key, not a position
Jump to page NYesNo (only next, previous, first)
Total countNeeds a separate COUNT(*)Not needed
NeedsAny ORDER BYA total order (unique tie-breaker) and a matching index
Typical useAdmin tables, small dataFeeds, infinite scroll, exports, public APIs

What the user sees versus what the database does.

ScreenNeedsBest fit
Infinite scroll feedNext page, no totalsKeyset
"Previous / Next" onlyTwo buttonsKeyset (both directions)
Numbered pager, small table (under about 10,000 rows)Page numbersOffset (paginate)
Numbered pager, large tablePage numbers, deep pages rareOffset with a capped depth, or hybrid
"Page 3 of 240" labelTotalEstimated or cached count, or drop the label
Public APIStable, forward-only, opaqueKeyset cursor
Bulk export, ETLAll rows onceKeyset or a server-side cursor

Counting options.

NeedTechniqueCost
Exact total, small tableSELECT count(*)One scan of the matching rows
Rough total, whole tablepg_class.reltuplesFree (catalog read), stale until VACUUM or ANALYZE
Rough total, filteredEXPLAIN (FORMAT JSON) row estimatePlanning only, accuracy depends on statistics
"1000+"SELECT count(*) FROM (SELECT 1 ... LIMIT 1001) tBounded by the cap
Exact total, big tableA cached or incrementally maintained countOne read per request

Why pagination is hard ​

Nobody wants 40 million rows in one response, so every list endpoint returns a slice. The trouble is that a slice has to be defined relative to something, and there are only two choices: relative to the top of the list (a position, which is offset) or relative to the last thing you showed (a key, which is keyset). Position is easy to say and expensive and fragile. A key is cheap and stable but cannot be addressed by number.

Weaker and simplerStronger and richer
Offset: any sort order, page numbers, easy to buildKeyset: constant cost, stable, but needs a unique total order, an index and a cursor
Count on every requestEstimated, capped or cached count
Server remembers nothingCursor carries state (and must be protected)
Works on any engineRow values work on PostgreSQL; MySQL and others need an expanded OR form

An everyday picture, reused below. A library shelf sorted by call number. "Books 301 to 350" forces the librarian to count from the first book every time, and if a book is returned in front of the counted range her count is off by one. "The 50 books after QA76.9" lets her walk straight to that call number and read forward; books returned elsewhere on the shelf do not matter.

OFFSET 900000 LIMIT 50WHERE (created_at, id) < ($1, $2) LIMIT 50index (created_at DESC, id DESC)entry 1 ... 900,000read, then thrown awayentries 900,001 ... +50walk from topcost grows with the page numbera row inserted above shifts every later pageindex (created_at DESC, id DESC)not visitednext 50 entriesB-tree seekO(log n)cost is the same on every pagethe boundary is a key, not a positionsame table, same index, same 50 rows returned

The left side scans and discards; the right side seeks. Both return the same 50 rows.

Three common misunderstandings, up front ​

  1. "An index makes OFFSET fast." It makes the walk cheaper (no sort), but the walk still happens: the server still produces every skipped row.
  2. "ORDER BY created_at is a deterministic order." Only if created_at is unique. Equal timestamps are returned in any order, and the order can differ between two executions of the same query.
  3. "Keyset is just offset with a WHERE." The mechanism is different: the database seeks into a B-tree by key. The WHERE is a range condition on an index, not a filter on rows already read.

Where it comes from ​

LIMIT and OFFSET are the SQL way to ask for "rows 51 to 100". The PostgreSQL manual states the rule that governs everything on this page. Paging only makes sense over a defined order, so the query needs an ORDER BY:

"When using LIMIT, it is important to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query's rows."

Markus Winand, who writes Use The Index, Luke, traces the cost to the standard itself. He quotes SQL:2023 on how an offset is applied: the rows are sorted, then "limited by dropping the number of rows specified in the <result offset clause> from the beginning". The offset is a bare number, so the database has nothing to work with except fetching and dropping that many rows. In his 2014 article (updated 2023) he names the alternative the seek method, also called keyset pagination.

Winand is candid about why offset persists: "the main reason to prefer offset over keyset pagination is the lack of tool support". Laravel's cursorPaginate() is one of the tools that changed this; his list of frameworks with keyset support names it as "Laravel 8.0+: CursorPaginator". His book chapter on Partial Results has three pages: top-N queries, paging through results (offset against seek), and window functions. The window-function variant (row_number() OVER (...) filtered by a range) is offset in disguise: the database still numbers every row before the filter, so it does not fix depth.

The same pattern appears, independently, in every large API: Stripe's starting_after, Slack's next_cursor, the GraphQL Cursor Connections Specification, DynamoDB's LastEvaluatedKey, Elasticsearch's search_after. They all reached the same answer for the same reason.

The concept catalogue ​

OFFSET and LIMIT: cost and instability Must-know ​

In plain words: OFFSET 900000 does not jump to row 900,001. The database produces the first 900,000 rows in order and throws them away, then returns the next 50.

Common misunderstanding: "My query only returns 50 rows, so it is cheap." The cost is in the rows produced, not the rows returned. Page 1 and page 18,000 return the same number of rows and differ by a factor of thousands in work.

Definition: LIMIT n OFFSET m returns rows m+1 to m+n of the sorted result. PostgreSQL §7.6: "The rows skipped by an OFFSET clause still have to be computed inside the server". An index on the sort key removes the sort but not the walk; it still visits (and, unless the index covers the query, fetches from the heap) every skipped entry.

The second problem is instability. The offset is a position, and positions move.

text
     User A (feed, newest first, 3 per page)      Writer
1    GET /orders?page=1   OFFSET 0 LIMIT 3
       -> ids 10, 9, 8
2                                                 INSERT order id=11  (newest)
3    GET /orders?page=2   OFFSET 3 LIMIT 3
       -> ids 8, 7, 6      <- id 8 shown twice
4                                                 DELETE order id=7
5    GET /orders?page=3   OFFSET 6 LIMIT 3
       -> ids 4, 3, 2      <- id 5 never shown (skipped)

Real scenario: a support dashboard that auto-refreshes while tickets arrive; an export job that pages through users while signups continue and misses or repeats users; a "latest orders" API consumed by a billing sync that therefore double-bills or never bills a row; a social feed where the last post of page 1 reappears at the top of page 2.

EngineWhat OFFSET costsHard limit
PostgreSQLProduces and discards m rows (index scan or sort)None, but slows linearly
MySQL InnoDBReads m rows (through an index, with a primary-key lookup per row unless covering)None
SQL ServerOFFSET m ROWS FETCH NEXT n ROWS ONLY reads m rowsNone
OracleOFFSET m ROWS FETCH NEXT n ROWS ONLY (12c+) reads m rowsNone
SQLiteReads m rowsNone
MongoDB skip()"The skip() method requires the server to scan from the beginning of the input results set before beginning to return results."None
Elasticsearch from/sizeEach shard loads the previous pages into memoryindex.max_result_window = 10,000 by default
DynamoDBNo offset at allCursor only (LastEvaluatedKey)

Fix: use keyset for anything deep or write-heavy; keep offset only where depth is bounded (see Choosing).

Keyset (seek) pagination Must-know ​

In plain words: instead of "skip 900,000", say "give me the rows that come after the last one I saw".

Common misunderstanding: "I need to store which page the user is on." You store the last row's sort key, not a page number, and you store it in the client's request (the cursor), not on the server.

Definition: the client sends the sort-key values of the last row it received; the server adds WHERE (sort keys) < or > (those values) to the same ORDER BY and fetches LIMIT n. Because the condition is a range on an indexed key, the B-tree is descended once to the boundary and then read forward n entries.

text
     Client                                Server / index (created_at DESC, id DESC)
1    GET /orders?limit=3
                                           ORDER BY ... LIMIT 4   (n+1)
2    <- ids 10, 9, 8 + next_cursor=(t8, 8)  (4th row only proves a next page exists)
3    [writer inserts id=11, deletes id=7]
4    GET /orders?limit=3&cursor=(t8, 8)
                                           WHERE (created_at, id) < (t8, 8) LIMIT 4
5    <- ids 6, 5, 4   (7 is gone, 11 is above the boundary: nothing repeated, nothing lost)

Three rules make it work: the sort must be total (unique), the comparison must match the sort direction, and an index must match both. Winand: "Paging requires a deterministic sort order." The costs you accept: no jumping to page 40, every client carries the cursor, and totals are not free (see counts).

sql
-- first page
SELECT id, customer_id, total_cents, created_at
FROM orders
ORDER BY created_at DESC, id DESC
LIMIT 51;                       -- n + 1: the extra row tells you "has next page"

-- next pages
SELECT id, customer_id, total_cents, created_at
FROM orders
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 51;

What provides it: PostgreSQL, Db2 (row values plus an index); MySQL, SQL Server and Oracle need the expanded OR form (see next section). The pattern needs no special engine support, only a B-tree index.

Fix / how to use it: the Go and Laravel implementations are in Solving the classic problems: ListOrders with size+1 rows in Go, and cursorPaginate() or a hand-rolled controller in Laravel.

Row-value comparison and index support Must-know ​

In plain words: (a, b) < (x, y) is SQL shorthand for "a is less than x, or a equals x and b is less than y". It is exactly the "comes after in sort order" test, written once.

Common misunderstanding: "(a, b) < (x, y) means a < x AND b < y." No. It is lexicographic: compare a first; look at b only when a ties.

Definition: PostgreSQL documents it in §9.26.5 (Row Constructor Comparison): "For the <, <=, > and >= cases, the row elements are compared left-to-right, stopping as soon as an unequal or null pair of elements is found." The operators must belong to a B-tree operator class, which is why a B-tree index on (a, b) can serve the comparison as an index condition.

text
     (created_at, id) < ('2026-11-25 10:00', 8)   -- is the row after the cursor in DESC order?
1    row (2026-11-25 10:05, 9):  created_at 10:05 > 10:00  -> false
2    row (2026-11-25 10:00, 9):  equal, then id 9 > 8      -> false
3    row (2026-11-25 10:00, 7):  equal, then id 7 < 8      -> true
4    row (2026-11-25 09:59, 99): created_at 09:59 < 10:00  -> true (id never looked at)
EngineRow-value range predicateIndex used as access predicateWhat to write
PostgreSQLYes (since 8.4, per Winand)Yes: Index Cond: (ROW(created_at, id) < ROW(...))(a, b) < ($1, $2)
MySQL 8.4Yes, correct resultsPartial: the manual shows c1=1 AND (c2,c3) > (1,1) using only the c1 prefix (key_len: 4)Expand to a < $1 OR (a = $1 AND b < $2)
SQL ServerNo row values at all (Winand, 2017 article)n/aExpanded OR form
OracleRow values exist but "cannot apply range operators on them (ORA-01796)"n/aExpanded OR form
SQLiteYes (3.15+), index use for the leading columnCheck EXPLAIN QUERY PLANRow values or OR form
CockroachDBYes (PostgreSQL dialect)Yes, verify with EXPLAIN(a, b) < ($1, $2)
MongoDBNo such syntax; compound range with $orIndex on {a: -1, _id: -1}{$or: [{a: {$lt: x}}, {a: x, _id: {$lt: y}}]}

Winand's note that "MySQL evaluates row value expressions correctly but cannot use them as access predicate during an index access" is from the 2017 text; the MySQL 8.4 manual shows partial use. The manual's own advice is the safe rule: "Thus, for better results, avoid mixing row constructors with AND/OR expressions. Use one or the other." For MySQL, write the expanded form and read the key_len in EXPLAIN.

sql
-- MySQL / SQL Server / Oracle: expanded seek condition, same meaning as the row value
WHERE created_at < :c
   OR (created_at = :c AND id < :i)
ORDER BY created_at DESC, id DESC
LIMIT 51;

An index that serves it (PostgreSQL and MySQL 8.0+ both accept descending index columns):

sql
CREATE INDEX orders_feed ON orders (created_at DESC, id DESC);
-- or just (created_at, id): a B-tree can be scanned backwards at the same cost

Fix: use the row-value form on PostgreSQL, the expanded form elsewhere, and prove the plan with EXPLAIN (see plan shapes).

Composite cursors with tie-breakers Must-know ​

In plain words: if two rows can have the same sort value, add something unique (the primary key) as the last sort column, or the page boundary will cut between them and lose or repeat one.

Common misunderstanding: "Timestamps are unique enough." Microsecond timestamps still collide in batch inserts (now() is the transaction start in PostgreSQL, so every row inserted in one transaction has the same created_at), in imports, and with low-resolution clocks (MySQL DATETIME without fractional seconds is one second).

Definition: the sort key is the tuple (user-visible column(s), unique column). The cursor stores the whole tuple. MongoDB says the same for skip(): sorting on duplicates "may return an inconsistent sort order for those duplicate fields over multiple executions", so include _id. Elasticsearch: "If you don’t include a tiebreaker field, your paged results could miss or duplicate hits."

text
     rows (created_at, id):  (10:00, 5)  (10:00, 6)  (10:00, 7)   page size 2, ORDER BY created_at DESC only
1    page 1 returns two of the three tied rows, e.g. 7, 6   cursor = created_at 10:00
2    page 2:  WHERE created_at < 10:00  -> row 5 is skipped for ever
     with (created_at, id): cursor = (10:00, 6) -> page 2: WHERE (created_at, id) < (10:00, 6) -> row 5
WhereTie-breaker
PostgreSQL, MySQL, SQL Server, OraclePrimary key id (or any unique column), always last in ORDER BY and in the index
Laravel cursorPaginate()You add orderByDesc('id'); the docs require "at least one unique column or a combination of columns that are unique"
MongoDB_id last in .sort({...})
ElasticsearchA unique field, or the implicit _shard_doc tiebreaker when you use a point in time
DynamoDBThe sort key is already part of the primary key (unique within a partition key)
StripeThe object ID is the cursor (starting_after); lists come back in reverse chronological order

Fix: always ORDER BY <sort>, id with the same direction, and the same columns in the index.

Descending and mixed order Important ​

In plain words: "newest first" flips every comparison from > to <. If one column ascends and another descends, a single row-value comparison cannot express it.

Common misunderstanding: "I can use (created_at, id) < ($1, $2) for ORDER BY created_at DESC, id ASC." That compares both columns in the same direction. It returns wrong rows silently: no error, just a boundary that is wrong for the second column.

Definition: a row-value comparison applies one operator to every pair. Mixed directions need the expanded form, and the index must have the same mixed directions to serve it.

ORDER BYSeek condition
created_at ASC, id ASC(created_at, id) > ($1, $2)
created_at DESC, id DESC(created_at, id) < ($1, $2)
created_at DESC, id ASCcreated_at < $1 OR (created_at = $1 AND id > $2)
score DESC, created_at DESC, id DESC(score, created_at, id) < ($1, $2, $3)
Previous page of a DESC feedflip operator and ORDER BY, fetch, then reverse the page in the application
sql
-- mixed order: newest first, ties by id ascending
CREATE INDEX orders_mixed ON orders (created_at DESC, id ASC);

SELECT id, created_at FROM orders
WHERE created_at < $1 OR (created_at = $1 AND id > $2)
ORDER BY created_at DESC, id ASC
LIMIT 51;

On PostgreSQL the planner may not turn that OR into a single index range. A widely used fix is a redundant range predicate on the leading column that the index can use as an access condition, with the OR as a filter:

sql
WHERE created_at <= $1
  AND (created_at < $1 OR id > $2)
ORDER BY created_at DESC, id ASC
LIMIT 51;

Verify it in your own EXPLAIN; the planner version matters. Laravel's cursorPaginate() builds exactly this nested OR per column and supports mixed directions because it applies > or < per column (internals).

NULLs in cursor columns Important ​

In plain words: NULL is neither less than nor greater than anything, so a row whose sort column is NULL can fall off the page boundary and never be returned.

Common misunderstanding: "ORDER BY x puts NULLs somewhere sensible, so the cursor will too." The ordering puts them somewhere (PostgreSQL sorts NULL as largest: last in ASC, first in DESC; MySQL treats NULL as smallest). The comparison returns unknown.

Definition: PostgreSQL §9.26.5: "If either of this pair of elements is null, the result of the row comparison is unknown (null)", and WHERE keeps only true. Laravel states the same limitation: "Columns with null values are not supported."

text
     ORDER BY shipped_at ASC NULLS LAST, id ASC          cursor = (NULL, 40)
1    WHERE (shipped_at, id) > (NULL, 40)  -> unknown for every row -> page is EMPTY
     the rows with shipped_at IS NULL and id > 40 vanish
SolutionHowCost
Forbid NULLsNOT NULL with a default or sentinel, e.g. 'infinity'::timestamptzSchema change, honest if the domain allows it
Sentinel via expression indexORDER BY coalesce(shipped_at, 'infinity'), id plus an index on that expressionIndex on an expression; same expression in the query
Two-region cursorCursor says which region it is in (non_null or null)More code, no schema change
IS NOT DISTINCT FROMshipped_at IS NOT DISTINCT FROM $1 for the equality partNot index-friendly on every engine
sql
-- ORDER BY shipped_at ASC NULLS LAST, id ASC
-- Cursor still in the non-NULL region (x = $1, id = $2):
WHERE (shipped_at > $1)
   OR (shipped_at = $1 AND id > $2)
   OR shipped_at IS NULL
-- Cursor already in the NULL region (id = $2):
WHERE shipped_at IS NULL AND id > $2

Fix: prefer NOT NULL columns for anything you page by. If the domain needs NULL, use the two-region form and store the region in the cursor.

Opaque cursors: encoding and signing Must-know ​

In plain words: the cursor is a string the client hands back unchanged. The client must not read it or build one.

Common misunderstanding: "Base64 hides the data." Base64 is an encoding, not protection. Anyone can decode eyJpZCI6MTV9, edit it and re-encode it. If a cursor can be forged, a client can probe your ordering, craft a boundary that triggers a slow query, or read rows another filter would hide.

Definition: an opaque cursor is a base64url token (RFC 4648 URL-safe alphabet, no padding) over a small payload: the sort-key values, a format version, an expiry and a fingerprint of the filter and sort. The Relay specification says it plainly: "The result of this field should be considered opaque by the client, but will be passed back to the server as described in the “Arguments” section below."

Response: encodeNext request: decode and verifylast rowcreated_at, idpayloadv, c, i, fp, expHMAC-SHA256secret keybase64urlbody.signaturenext_cursoropaque to clientfp = hash(filter + sort). exp = now + TTL. v = format version. Encoding is not encryption.cursor=...from the clientverify HMACconstant timev, exp, fpversion, TTL, filterWHERE (c,i) < (?,?)row-value seekLIMIT n+1extra row = has nextany failure: HTTP 400 or 422
LevelWhat it isProtects against
Raw column values in the URL (?after_id=15)PlainNothing; clients start depending on it
base64url of JSON (Laravel cursorPaginate(): {"id":15,"_pointsToNextItems":true})EncodingCasual reading, URL-unsafe characters
base64url + HMAC-SHA256 signatureIntegrityEditing, forging, replaying with changed values
Encrypted (AES-GCM, Laravel Crypt)Confidentiality + integrityAlso hides the values (rarely needed; see below)
Server-side token (the cursor is a random id; state in Redis)StatefulEverything, at the price of storage and expiry
text
     Client                                     Server (HMAC key K)
1    GET /orders?limit=50
2                                               last row = (t8, 8); fp = H(status=paid, sort=created_at desc)
                                                body = b64url({"v":1,"c":t8,"i":8,"f":fp,"exp":now+3600})
                                                sig  = b64url(HMAC-SHA256(K, body))
3    <- next_cursor = body.sig
4    GET /orders?limit=50&cursor=body.sig
5                                               verify sig (constant time) -> v -> exp -> fp ; any failure = 400
6                                               WHERE (created_at, id) < (t8, 8)

Rules: verify the signature before parsing the body; compare with a constant-time function (hmac.Equal in Go, hash_equals in PHP); bind the cursor to the filter and sort so it cannot be replayed on another query; never put secrets or personal data in it; do not rely on the cursor to hide row ids (an id leaks ordering; signing prevents editing, not reading). A signed cursor is integrity, not secrecy: encrypt only if the key values are sensitive.

Fix: the signed Go codec and the Laravel SignedCursor class are in Solving the classic problems.

Cursor expiry and versioning Good to know ​

In plain words: a cursor is a promise about a sort order. When the sort order changes, or the cursor is a week old, the promise is void, so the server should refuse it instead of guessing.

Common misunderstanding: "A cursor is valid for ever." After a deploy that changes the sort (a new tie-breaker, a different index, a renamed column), an old cursor means something else, and the result is silently wrong, not an error.

Definition: put a version number (v) in the payload; on a breaking change, bump it and reject older versions with 400 and a message that tells the client to restart from the first page. Put an expiry (exp) so a leaked cursor is not a permanent key, and so you can retire a format after one TTL. Rotate signing keys by accepting the previous key for one TTL (a kid header in the payload).

FailureStatusResponse bodyClient action
Bad signature, malformed400invalid_cursorStop; do not retry the same cursor
Expired400 (or 410 Gone)cursor_expiredRestart from the first page
Old version400cursor_versionRestart from the first page
Cursor belongs to another filter400cursor_mismatchRestart
Valid, but the row was deleted200normal pageNothing: a range predicate does not need the row to exist

The last row is worth remembering: keyset keeps working when the cursor row has been deleted, because the boundary is a value, not a row to find. Offset has no such property.

Total counts, estimated counts and count caching Must-know ​

In plain words: "page 3 of 240" needs the total number of matching rows, and counting a big table is itself a big scan.

Common misunderstanding: "COUNT(*) is cheap, the database keeps the count." PostgreSQL does not (MVCC: each transaction sees different rows, so there is no single count; see MVCC & VACUUM). InnoDB also scans (an index) for COUNT(*). MyISAM keeps an exact count, which is the source of the myth. paginate() in Laravel runs it on every request.

Definition: a count can be exact (scan), estimated (statistics), capped, or cached.

TechniqueSQLAccuracyCost
ExactSELECT count(*) FROM orders WHERE status = 'paid'ExactScans the matching rows or an index
Table estimate, PostgreSQLSELECT reltuples::bigint FROM pg_class WHERE oid = 'orders'::regclassStale until VACUUM/ANALYZE; documented as "only an estimate used by the planner"; -1 means never analyzed (PostgreSQL 14+)Free
Filtered estimateEXPLAIN (FORMAT JSON) SELECT 1 FROM orders WHERE status='paid' then read Plan RowsDepends on statistics and the filterPlanning only
CappedSELECT count(*) FROM (SELECT 1 FROM orders WHERE ... LIMIT 1001) tExact up to the cap, then "1000+"Bounded
InnoDB estimateSELECT TABLE_ROWS FROM information_schema.TABLES WHERE ... or SHOW TABLE STATUSApproximateFree
CachedRedis/Cache::remember with a short TTL, keyed by filterAs stale as the TTLOne read
MaintainedA counter table updated by triggers or eventsExact, eventuallyWrite overhead
Drop itNo total; show "Next" and a has_more flagn/aNone

MySQL's SQL_CALC_FOUND_ROWS with FOUND_ROWS() was the classic one-query trick, but it forces the server to compute the full result and is deprecated; use a second COUNT(*) or one of the above. The Relay connections spec leaves a total out of the required fields (a connection "may have additional fields"), so servers that offer totalCount add it themselves and usually estimate it.

sql
-- estimate for the whole table (PostgreSQL)
SELECT reltuples::bigint AS approx_rows
FROM pg_class
WHERE oid = 'orders'::regclass;

-- estimate for a filtered query: read "Plan Rows" at the top node
EXPLAIN (FORMAT JSON) SELECT 1 FROM orders WHERE status = 'paid';

Fix: the Go helpers TableEstimate, QueryEstimate, CappedCount and a TTL Cache are in Solving the classic problems. In Laravel, simplePaginate() and cursorPaginate() skip the count, and you attach your own with Cache::remember.

Infinite scroll vs numbered pages; jumping to page N Important ​

In plain words: infinite scroll only ever asks "what is after what I have", which keyset answers perfectly. A numbered pager asks "give me page 40", which needs to know how many rows come before page 40.

Common misunderstanding: "Keyset can jump to page N if I do the maths." It cannot: with deletions and gaps in ids, page 40 starts at an unknown key. Aaron Francis puts it as: "pages are not directly addressable when using cursor pagination". Winand: "keyset pagination has some limitations: most notably that you cannot directly navigate to arbitrary pages".

UIQuestionMethod
Infinite scroll, feed, "Load more"After this rowKeyset
Previous / Next buttonsAfter or before this rowKeyset, both directions
Numbered pager 1 2 3 ... 240Rows m to m+nOffset, or hybrid
"Jump to date"After this dateKeyset with a synthetic cursor (date, 0)
Alphabet index A-ZAfter "M"Keyset on the name column
Admin grid with sort by any column and page numbersArbitraryOffset, small data; or search index

Why real products rarely need page 40: nobody reads page 40. Google, shops and feeds cap result depth (Elasticsearch's default is 10,000 hits), or encourage filters. If a user truly needs "the 40th page", they need a filter or a date jump, not a page number.

Fix: if the product demands numbered pages, cap the depth (for example 100 pages), show an estimated total, or use the hybrid.

Hybrid: keyset plus sparse offsets Good to know ​

In plain words: keep a small table of "bookmarks": the key of every 1,000th row. To open page 40, start at the nearest bookmark below it and use a small offset from there.

Common misunderstanding: "Hybrid is a compromise that is worse at both." It bounds the offset to the bookmark spacing (at most 999 rows skipped) while still giving numbered pages, at the price of a stale bookmark table.

Definition: compute bookmarks with a window function in a background job; store them (a table or cache); at read time choose the bookmark, then WHERE (created_at, id) < bookmark ... OFFSET r LIMIT n with r under the spacing.

sql
-- build bookmarks: key of every 1000th row of the feed (run on a schedule)
SELECT created_at, id, rn
FROM (
    SELECT created_at, id,
           row_number() OVER (ORDER BY created_at DESC, id DESC) AS rn
    FROM orders WHERE status = 'paid'
) t
WHERE rn % 1000 = 1;

-- page 40 at 50 per page = rows 1951..2000: nearest bookmark is rn 1001, so skip 950 from it
SELECT id, created_at FROM orders
WHERE status = 'paid' AND (created_at, id) <= ($bm_created, $bm_id)
ORDER BY created_at DESC, id DESC
OFFSET 950 LIMIT 50;

Bookmarks drift when rows are inserted (each bookmark moves by the number of inserts above it), so pages are approximate. That is acceptable for browsing, not for exports. Search engines do something similar internally with skip lists and shard-local ranges.

Filters and joins Important ​

In plain words: the index has to match the filter and the sort: equality columns first, then the sort columns. A join that multiplies rows breaks the cursor.

Common misunderstanding: "I can paginate a join like any query." A one-to-many join returns the parent once per child, so LIMIT 50 can return fewer than 50 parents and the cursor can land in the middle of one parent's children.

SituationProblemFix
WHERE status = 'paid'Index on (created_at, id) alone cannot seek within the statusIndex (status, created_at, id): equality column first
Two filters, optionalOne index per combination explodesPartial indexes for the hot filters; otherwise accept a filter in the plan
WHERE status IN ('paid','shipped')Two index ranges, mergedPostgreSQL may use a merge or Sort; consider two queries, or a partial index on the union
One-to-many joinParents repeatedPage the parent table by its own keys, then join the page
Many-to-many joinSamePage ids in a subquery or CTE, then join
Sort by an aggregate (COUNT, SUM)Cannot index; every cursor needs the aggregatePre-aggregate into a column or materialised view, or a search engine
Sort by a joined columnCursor columns are on another tableDenormalise the sort key onto the paged table
LIKE '%x%', full-text relevanceNot a B-tree orderFull-text search: search_after style cursors
OR across columnsIndex cannot serve itUNION ALL of two keyset queries, merged
sql
-- page parents first, join afterwards: exactly 50 parents per page
WITH page AS (
    SELECT id, created_at FROM orders
    WHERE status = 'paid' AND (created_at, id) < ($1, $2)
    ORDER BY created_at DESC, id DESC
    LIMIT 51
)
SELECT p.id, p.created_at, i.sku, i.qty
FROM page p
JOIN order_items i ON i.order_id = p.id
ORDER BY p.created_at DESC, p.id DESC, i.id;

Laravel: cursorPaginate() requires the paged columns to belong to the table being paginated, so for joins you paginate the parent and use with('items') (eager loading), which issues one extra WHERE order_id IN (...) query and avoids the row multiplication.

Deep pagination on replicas Important ​

In plain words: reports and exports are often sent to a read replica. Replicas lag, and each page request may go to a different replica.

Common misunderstanding: "A replica is a copy, so page 2 is the same as page 2 on the primary." Two requests may hit two replicas at two different lags, so offset pages can overlap or skip more than they would on one server.

Definition: offset needs one consistent state across all page requests; keyset needs only that the boundary key means the same thing on the next server, which it does.

text
     Client                          Replica R1 (lag 0s)        Replica R2 (lag 4s)
1    page 1 (OFFSET 0)  ---------->  rows 10..8
2    [row 11 committed on primary]
3    page 2 (OFFSET 3)  ------------------------------------>   sees rows ..8,7,6  (no 11 yet): consistent
4    page 2 on R1 instead:  sees 11,10,9,8,7,6...  -> OFFSET 3 returns 8,7,6 again (duplicate)
     keyset: WHERE (created_at,id) < (t8,8) returns 7,6,5 on both replicas
ConcernPostgreSQLMySQLMitigation
Lag between pagesStreaming replication lagReplica lag, Seconds_Behind_SourceKeyset; sticky routing (same replica per session)
Long page queries killedHot standby cancels conflicting queries: "canceling statement due to conflict with recovery"; max_standby_streaming_delay, hot_standby_feedbackNot applicable (no WAL replay conflicts)Keep page queries short (keyset), or run exports with a snapshot on a dedicated replica
Read-your-writesNew row not on replica yetSameRead the first page from the primary after a write, or use Laravel's sticky option
ExportsLong transaction on a replica holds back cleanupSameA dedicated replica and hot_standby_feedback knowingly

PostgreSQL's documentation warns that tables "regularly and heavily updated on the primary server will quickly cause cancellation of longer running queries on the standby". Deep offset queries are exactly the long running ones. Replication, lag and failover are covered in Replication & Failover.

MySQL: LIMIT with ORDER BY, late row lookup and the deferred join Important ​

In plain words: MySQL, when ORDER BY is not served by an index, sorts everything that matches, then applies the LIMIT. When it is, it stops early. And with a big OFFSET it reads every wide row it skips.

Common misunderstanding: "LIMIT makes MySQL read only that many rows." The manual: "If you combine LIMIT row_count with ORDER BY, MySQL stops sorting as soon as it has found the first row_count rows of the sorted result". That helps a filesort stop sorting; the rows are still all selected. "If a filesort must be done, all rows that match the query without the LIMIT clause are selected, and most or all of them are sorted, before the first row_count are found." Only an index-ordered scan is fast.

Definition: the manual also states the determinism rule: "If multiple rows have identical values in the ORDER BY columns, the server is free to return those rows in any order, and may do so differently depending on the overall execution plan." One factor is LIMIT itself, so ORDER BY category with and without LIMIT may return ties in a different order. This is why a unique tie-breaker is mandatory, not optional.

Late row lookup. With a secondary index, InnoDB finds the matching index entries and then looks each row up in the clustered (primary key) index. With OFFSET 150000 it does 150,000 of those lookups for rows it throws away. The optimisation is to postpone the lookup (late row lookup) until after the offset and limit have been applied, using only the index. The deferred join is the SQL form of that idea. Aaron Francis: "A deferred join is a technique that defers access to requested columns until after the offset and limit have been applied." Note: "late row lookup" and "deferred join" are community names (the MySQL manual does not use them); the effect can be confirmed in EXPLAIN as Using index in the inner query.

sql
-- slow: 150,050 row lookups, 150,000 thrown away
SELECT * FROM contacts ORDER BY id LIMIT 50 OFFSET 150000;

-- deferred join: the inner query reads only ids from an index
SELECT c.*
FROM contacts c
JOIN (
    SELECT id FROM contacts ORDER BY id LIMIT 50 OFFSET 150000
) AS page USING (id)
ORDER BY c.id;
TechniqueKeeps page numbers?Stable under writes?GainWhere
Plain offsetYesNoNoneEverywhere
Deferred joinYesNoLarge when rows are wide or the index covers the inner queryMySQL; also helps PostgreSQL when the inner query is index-only
KeysetNoYesConstant costEverywhere
HybridYes (approx.)MostlyBounded offsetEverywhere

The deferred join helps with cost, not with drift. Laravel: joinSub() builds it (snippet), and the community package hammerstonedev/fast-paginate (linked from Aaron Francis's article) packages the same idea.

PostgreSQL has no equivalent of InnoDB's clustered lookup, but an Index Only Scan gives the same benefit when the inner query selects only indexed columns and the visibility map is up to date.

Per-engine and per-API behaviour ​

What each database really does ​

ProductOffset syntaxKeyset supportStable cursor primitiveGotcha
PostgreSQLLIMIT n OFFSET mRow values with index accessServer-side cursor (DECLARE/FETCH), see Cursors & StreamingWithout a unique ORDER BY: "an unpredictable subset"; reltuples is -1 if never analyzed
MySQL 8.4 / InnoDBLIMIT n OFFSET m or LIMIT m, nExpanded OR form; row values only partly index-servedNone portableTies returned in plan-dependent order; filesort when ORDER BY has no index
SQL ServerORDER BY ... OFFSET m ROWS FETCH NEXT n ROWS ONLY (2012+; ORDER BY mandatory)Expanded OR formNone portableNo row-value syntax at all
OracleOFFSET m ROWS FETCH FIRST n ROWS ONLY (12c+), older ROWNUMExpanded OR formCursor (PL/SQL REF CURSOR)ORA-01796 on range operators over row values
SQLiteLIMIT n OFFSET mRow values (3.15+) or OR formNoneSingle-writer: pages drift only on write; embedded use rarely needs deep pages
MongoDB.skip(m).limit(n)Range query on an indexed field (usually _id)Server-side cursor with getMore batchesskip() scans from the start; ObjectId is not strictly monotonic
CockroachDBPostgreSQL dialectRow valuesNoneDistributed scans: deep offset touches many ranges
Elasticsearch / OpenSearchfrom + size (max 10,000 by default)search_after, ideally with a point in timePoint in time (PIT)Each shard loads the previous pages into memory
DynamoDBNoneExclusiveStartKey / LastEvaluatedKeyThe key itself1 MB page cap; a filter can leave a page empty
RedisZRANGE ... LIMIT offset count on sorted sets, LRANGE on listsScore range with an exclusive bound, e.g. ZRANGE k (score +inf BYSCORE LIMIT 0 50SCAN opaque cursor (returns 0 at the end)Offset on sorted sets and LRANGE on lists still walk

MongoDB: skip/limit vs a range on _id Important ​

In plain words: skip(900000) makes MongoDB walk 900,000 documents. A range query on _id seeks the index.

Common misunderstanding: "ObjectId order is creation order." Not strictly: it has one-second resolution, and clients generate it, so ids created in the same second or on different clocks can interleave. Use _id as a unique tiebreaker, not as a clock.

Definition: the MongoDB manual says: "The skip() method requires the server to scan from the beginning of the input results set before beginning to return results." Its recommended alternative is a range query: "Range queries can use indexes to avoid scanning unwanted documents, typically yielding better performance as the offset grows compared to using skip() for pagination."

js
// offset: slower with every page
db.orders.find({status: "paid"}).sort({createdAt: -1, _id: -1}).skip(900000).limit(50)

// keyset: compound index {status: 1, createdAt: -1, _id: -1}
db.orders.find({
  status: "paid",
  $or: [
    {createdAt: {$lt: lastCreatedAt}},
    {createdAt: lastCreatedAt, _id: {$lt: lastId}}
  ]
}).sort({createdAt: -1, _id: -1}).limit(50)

Elasticsearch: from/size vs search_after Important ​

In plain words: a search is spread over shards, so "page 1000" means every shard sorts its top 10,000 and the coordinator merges them. That is why Elasticsearch simply refuses.

Common misunderstanding: "Raise index.max_result_window and deep pages work." You trade the error for memory and CPU on every node.

Definition: "By default, you cannot use from and size to page through more than 10,000 hits. This limit is a safeguard set by the index.max_result_window index setting. If you need to page through more than 10,000 hits, use the search_after parameter instead." search_after takes the sort values of the last hit. Because a refresh between requests can reorder results, you open a point in time (POST /my-index/_pit?keep_alive=1m) and pass its id; a PIT also adds the implicit _shard_doc tiebreaker.

json
POST /_search
{
  "size": 50,
  "query": { "match": { "title": "pagination" } },
  "pit": { "id": "<pit id>", "keep_alive": "1m" },
  "sort": [ { "published_at": "desc" }, { "_shard_doc": "desc" } ],
  "search_after": [1463538857, 4294967297]
}

DynamoDB: LastEvaluatedKey Important ​

In plain words: DynamoDB has no offset. A Query returns up to 1 MB (or your Limit) plus a LastEvaluatedKey; you pass it back as ExclusiveStartKey.

Common misunderstanding: "A non-empty LastEvaluatedKey means there is more data." Not necessarily. The docs: "The only way to know when you have reached the end of the result set is when LastEvaluatedKey is empty." A non-empty key only means the read stopped at a page boundary, and with a FilterExpression a page "can return zero matching items and still include a LastEvaluatedKey" (filters apply after the read).

go
// Go (aws-sdk-go-v2): loop until the key is nil
for {
    out, err := client.Query(ctx, &dynamodb.QueryInput{
        TableName:                 aws.String("Orders"),
        KeyConditionExpression:    aws.String("customer_id = :c"),
        ExpressionAttributeValues: map[string]types.AttributeValue{":c": &types.AttributeValueMemberS{Value: "42"}},
        ExclusiveStartKey:         startKey, // nil on the first call
        Limit:                     aws.Int32(50),
    })
    if err != nil { return err }
    handle(out.Items)
    if out.LastEvaluatedKey == nil { break }
    startKey = out.LastEvaluatedKey
}

How public APIs paginate ​

APIRequest parametersResponse fieldsEnd of dataNotes
Stripelimit (1-100, default 10), starting_after, ending_before (object IDs)data, has_morehas_more: falseCursor is an object ID; "These parameters are mutually exclusive"; Search endpoints use next_page
Slack Web APIcursor, limit (max 1000, recommended 100-200)response_metadata.next_cursor"An empty, null, or non-existent next_cursor"May return fewer than limit and still have more
GraphQL Relay connectionsfirst/after, last/beforeedges { node cursor }, pageInfo { hasNextPage hasPreviousPage startCursor endCursor }hasNextPage: falseCursors are opaque strings
GitHub RESTper_page, page or cursor, depending on endpointLink response headerNo rel="next"RFC 8288 web links
Elasticsearchsize, search_after, pitHits with sort valuesFewer hits than sizeNeeds a tiebreaker
DynamoDBLimit, ExclusiveStartKeyLastEvaluatedKeyKey absentNot "page full"
MongoDB driversCursor with batchSizeCursor id for getMoreCursor id 0A server cursor, not a page

Stripe: "The starting_after parameter returns objects listed after the named object." The Slack docs warn: "Avoid the temptation to check the size of results against the limit to conclude the results have been completely returned." Both say the same thing as DynamoDB: the end marker, not a short page, signals the end.

GraphQL Cursor Connections. A connection is an object whose name ends in Connection with edges and pageInfo; each edge has node and cursor. Arguments are first/after for forward and last/before for backward. pageInfo has hasNextPage, hasPreviousPage, startCursor, endCursor. The spec: "The result of this field should be considered opaque by the client". It also fixes the ordering rule: "the ordering must be consistent from page to page" and the same for first/after and last/before.

graphql
query {
  orders(first: 50, after: "WyIyMDI2LTExLTI1VDEwOjAwOjAwWiIsOF0") {
    edges { cursor node { id totalCents } }
    pageInfo { hasNextPage endCursor }
  }
}

Link headers (RFC 8288). The RFC defines the Link header: "The Link header field provides a means for serialising one or more links into HTTP headers." The relation names next, prev, first, last come from the IANA link-relations registry; the RFC defines the header syntax, not pagination. GitHub: "When a response is paginated, the response headers will include a link header." The advantage is that the client follows URLs instead of building them, so you can change the cursor format freely.

text
HTTP/1.1 200 OK
Link: <https://api.example.com/orders?cursor=eyJ2IjoxfQ.x1y2&limit=50>; rel="next",
      <https://api.example.com/orders?limit=50>; rel="first"

Laravel's paginators produce this shape for you in JSON (next_page_url, prev_page_url, links), and you can add the header yourself with response()->json($page)->header('Link', ...).

Mechanics ​

Plan shapes: proving which one you have Must-know ​

The plans below are the shape PostgreSQL produces for the lab table (1,000,000 rows, index orders_feed (created_at DESC, id DESC)). Row counts and timings depend on hardware and statistics; the shape and the actual rows are what matter.

text
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, customer_id, total_cents, created_at FROM orders
ORDER BY created_at DESC, id DESC LIMIT 50 OFFSET 900000;

 Limit  (actual rows=50 loops=1)
   ->  Index Scan using orders_feed on orders  (actual rows=900050 loops=1)
 Buffers: shared hit/read = hundreds of thousands of pages   <- the discarded rows were fetched

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, customer_id, total_cents, created_at FROM orders
WHERE (created_at, id) < ('2026-11-01 00:00', 123456)
ORDER BY created_at DESC, id DESC LIMIT 50;

 Limit  (actual rows=50 loops=1)
   ->  Index Scan using orders_feed on orders  (actual rows=50 loops=1)
         Index Cond: (ROW(created_at, id) < ROW('2026-11-01 00:00:00+00'::timestamptz, 123456))
 Buffers: shared hit/read = a few pages
Plan lineOffset meansKeyset means
Index Scan actual rows=Offset + limit (900,050): the skipped rows were produced50
Index Cond: (ROW(a, b) < ROW(...))absentThe row comparison is an access predicate (a real seek)
Filter: ... plus Rows Removed by FilterLarge number = predicate applied after reading, not a seekShould be 0 or tiny; if large, the index does not match
Sort / Sort Method: top-N heapsortIndex does not match ORDER BYFix the index
Index Only Scan and Heap FetchesCheaper skip when the index covers the columnsEven cheaper
MySQL key_lenn/aFull key length means all columns seek; shorter means the row constructor used only a prefix
MySQL Extra: Using filesortSort of all matching rowsSame problem; fix the index
MySQL Extra: Using indexCovering indexThe deferred join's inner query should show it

The MySQL manual's example makes the key_len rule concrete: for a primary key on (c1, c2, c3), WHERE c1=1 AND (c2,c3) > (1,1) shows key_len: 4 (only c1), while c1 = 1 AND (c2 > 1 OR ((c2 = 1) AND (c3 > 1))) shows key_len: 12 and type: range. This is exactly the shape of status = 'paid' plus a keyset condition.

Laravel internals: paginate, simplePaginate, cursorPaginate Must-know ​

MethodSQL it issuesCount querytotal()/page numbersCursor
paginate()select count(*) ... then ... limit 50 offset 100Yes, every requestYes (LengthAwarePaginator)page number in the query string
simplePaginate()... limit 51 offset 100 (perPage + 1)NoNo: "Not available when using simplePaginate"page number
cursorPaginate()... where (...) order by ... limit 51NoNo; only Next/Previouscursor token

How cursorPaginate() builds its condition (read from Illuminate\Database\Concerns\BuildsQueries::paginateUsingCursor in the 13.x source, saved with this page's sources): for each ORDER BY column in order, it adds column > cursorValue (ascending) or column < cursorValue (descending), and for every column except the last it ORs in "this column equals the cursor value, and the next condition holds". It then applies limit($perPage + 1). So for ORDER BY created_at DESC, id DESC and a cursor {created_at: T, id: 8} the SQL is, derived from that code (extra parentheses included):

sql
select * from "orders"
where "status" = 'paid'
  and ("created_at" < 'T' or ("created_at" = 'T' and ("id" < 8)))
order by "created_at" desc, "id" desc
limit 51

It is OR-expanded, not row-value, so it works on every driver and handles mixed directions. On PostgreSQL the planner may serve it with a partial index condition plus filter; check EXPLAIN, and consider the redundant created_at <= 'T' trick from mixed order in a hand-rolled version.

The cursor itself (Illuminate\Pagination\Cursor) is base64 of json_encode of the order columns plus _pointsToNextItems, with +, /, = replaced by -, _ and nothing. The docs' example, eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0, decodes to {"id":15,"_pointsToNextItems":true}. It is not signed. _pointsToNextItems: false means "previous page": Laravel then reverses the ORDER BY, queries, and reverses the result.

The documented limits of cursorPaginate(): Next/Previous links only, an order on "at least one unique column or a combination of columns that are unique", "Columns with null values are not supported", and "Query expressions in 'order by' clauses are supported only if they are aliased and added to the 'select' clause as well." Use withQueryString() on a paginator to keep filters in the generated links, and a cursorName argument for several paginators on one page.

chunkById, lazyById and cursor() Important ​

In plain words: these are the "walk the whole table" tools. chunkById is keyset in disguise; chunk() is offset; cursor() is a streaming read.

Common misunderstanding: "chunk() and chunkById() are the same, ById is just a style." If the loop updates the column it filters on, chunk() (offset) skips rows. The docs: "Internally, the chunkById method will always retrieve models with an id column greater than the last model in the previous chunk."

text
     chunk(100)  : users WHERE active = 1 ... offset 0, then offset 100 ...   (loop sets active = 0)
1    pass 1: rows 1-100 set active=0, now they no longer match
2    pass 2: offset 100 skips 100 rows that moved up -> rows 101-200 are never processed
     chunkById(100): WHERE id > 100 ORDER BY id LIMIT 100 -> correct
MethodMechanismMemorySafe while updating the filter column?
chunk()limit/offset per chunkOne chunkNo
chunkById()where id > :last order by id limit n (forPageAfterId)One chunkYes
lazyById()Same as chunkById, as a LazyCollectionOne chunkYes
lazy()Offset chunks as a lazy collectionOne chunkNo
cursor()One query, rows hydrated one at a time over an unbuffered resultOne model (plus driver buffering, see below)Not applicable (single snapshot)

The docs say cursor() "will only execute a single database query" and that "only one Eloquent model is kept in memory at any given time", but it cannot eager load. PDO MySQL buffers the whole result by default and PDO pgsql (libpq) also reads the whole result into the client, so cursor() saves model hydration, not necessarily driver memory. The full discussion (server-side cursors, WITH HOLD, streaming exports) is in Cursors & Streaming Results.

Go: keyset loops and the streaming pointer Good to know ​

In Go the standard library gives you database/sql rows that stream (rows.Next()), and pgx adds true server-side cursors and CopyTo. For a whole-table walk, keyset in a loop is the portable answer:

go
// walk orders in id order, 1000 at a time, without OFFSET
last := int64(0)
for {
    rows, err := db.QueryContext(ctx,
        `SELECT id, total_cents FROM orders WHERE id > $1 ORDER BY id LIMIT 1000`, last)
    if err != nil { return err }
    n := 0
    for rows.Next() {
        var id, total int64
        if err := rows.Scan(&id, &total); err != nil { rows.Close(); return err }
        last, n = id, n+1
    }
    if err := rows.Close(); err != nil { return err }
    if n < 1000 { return nil }
}

Each iteration is its own short statement (no long transaction, no held snapshot), which is why this is friendlier to replicas and vacuum than one giant cursor. When you need one consistent snapshot for the whole export, use a transaction-scoped cursor instead; see cursors-streaming for pgx's Query streaming and the memory trade-offs.

Errors and statuses you will meet Must-know ​

WhereCode / messageMeaningAction
PostgreSQL2201W invalid_row_count_in_limit_clause, 2201X invalid_row_count_in_result_offset_clauseNegative LIMIT or OFFSETValidate user input before the query
PostgreSQL standbycanceling statement due to conflict with recovery (SQLSTATE 40001)Long page query on a hot standby conflicted with WAL replayRetry; shorten queries; max_standby_streaming_delay
PostgreSQL57014 query_canceledstatement_timeout hit by a deep offsetSwitch to keyset; cap depth
MySQL1064 syntax error near '50'LIMIT placeholder bound as a stringBind integers, or disable emulated prepares
MySQL1038 out of sort memoryfilesort over too many rowsAdd the matching index
ElasticsearchResult window is too large, from + size must be less than or equal to: [10000]Offset past index.max_result_windowUse search_after + PIT
DynamoDBValidationException (invalid ExclusiveStartKey)Cursor does not match the key schemaRestart from the first page
HTTP400 / 422Bad, forged, expired cursor or wrong filterClient restarts from page 1
HTTP429Client is hammering deep pagesCap depth and rate limit

Solving the classic problems ​

ProblemPreferred solutionAdvantageCost / limit
Deep feed gets slowKeyset on (created_at, id)Constant costNo page jump
Duplicates and gaps while readingKeysetBoundary is a keyCursor must be total
Forged or stale cursorsHMAC-signed, versioned, expiring cursorIntegrity, clean failureKey management
"Page 3 of 240" is slowEstimated, capped or cached countBounded or freeApproximate
Numbered pager on a big tableCap depth, or hybrid with bookmarksPage numbersApproximate pages
MySQL offset with wide rowsDeferred joinSkips on the index onlyStill drifts
Walk the whole tablechunkById / keyset loopSafe under updatesNot one snapshot
Join multiplies rowsPage parents, then joinExactly n parentsTwo-step query

A keyset feed ​

SQL first, then Go, then Laravel.

sql
-- index serving the feed
CREATE INDEX orders_paid_feed ON orders (status, created_at DESC, id DESC);

-- page query (PostgreSQL row value; MySQL: use the expanded OR form)
SELECT id, customer_id, total_cents, created_at
FROM orders
WHERE status = 'paid' AND (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 51;

Go, before (offset): page N skips (N-1) x size rows, plus a second count(*).

go
// Package before shows offset pagination. Page N asks the database to skip
// (N-1)*size rows. The database still reads, sorts and discards those rows.
package before

import (
	"context"
	"database/sql"
	"fmt"
	"time"
)

type Order struct {
	ID         int64
	CustomerID int64
	TotalCents int64
	CreatedAt  time.Time
}

// ListOrders returns one page of orders, newest first.
func ListOrders(ctx context.Context, db *sql.DB, page, size int) ([]Order, error) {
	if page < 1 {
		page = 1
	}
	offset := (page - 1) * size

	rows, err := db.QueryContext(ctx, `
		SELECT id, customer_id, total_cents, created_at
		FROM orders
		ORDER BY created_at DESC, id DESC
		LIMIT $1 OFFSET $2`, size, offset)
	if err != nil {
		return nil, fmt.Errorf("list orders: %w", err)
	}
	defer rows.Close()

	var out []Order
	for rows.Next() {
		var o Order
		if err := rows.Scan(&o.ID, &o.CustomerID, &o.TotalCents, &o.CreatedAt); err != nil {
			return nil, fmt.Errorf("scan order: %w", err)
		}
		out = append(out, o)
	}
	return out, rows.Err()
}

// CountOrders is the extra full-table query a "page 3 of 240" UI needs.
func CountOrders(ctx context.Context, db *sql.DB) (int64, error) {
	var n int64
	if err := db.QueryRowContext(ctx, `SELECT count(*) FROM orders`).Scan(&n); err != nil {
		return 0, fmt.Errorf("count orders: %w", err)
	}
	return n, nil
}

Go, after (keyset): the cursor carries (created_at, id); the handler fetches size+1 rows.

go
// Package after shows keyset (seek) pagination. The client sends back an opaque
// cursor holding the (created_at, id) of the last row it saw, and the query
// asks for rows that sort strictly after it. An index on (created_at, id)
// lets the database start at that point instead of counting from the top.
package after

import (
	"context"
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"time"
)

var ErrInvalidCursor = errors.New("invalid cursor")

type Order struct {
	ID         int64
	CustomerID int64
	TotalCents int64
	CreatedAt  time.Time
}

// cursorPayload is the inside of the cursor. Clients must treat the encoded
// string as opaque, so the field names and encoding can change later.
type cursorPayload struct {
	CreatedAt time.Time `json:"c"`
	ID        int64     `json:"i"`
}

// EncodeCursor turns the last row of a page into an opaque, URL-safe string.
// time.Time keeps nanoseconds, so microsecond timestamps round-trip exactly.
func EncodeCursor(o Order) (string, error) {
	b, err := json.Marshal(cursorPayload{CreatedAt: o.CreatedAt, ID: o.ID})
	if err != nil {
		return "", fmt.Errorf("encode cursor: %w", err)
	}
	return base64.RawURLEncoding.EncodeToString(b), nil
}

// DecodeCursor reverses EncodeCursor and rejects anything malformed.
func DecodeCursor(s string) (cursorPayload, error) {
	b, err := base64.RawURLEncoding.DecodeString(s)
	if err != nil {
		return cursorPayload{}, ErrInvalidCursor
	}
	var p cursorPayload
	if err := json.Unmarshal(b, &p); err != nil {
		return cursorPayload{}, ErrInvalidCursor
	}
	if p.ID == 0 || p.CreatedAt.IsZero() {
		return cursorPayload{}, ErrInvalidCursor
	}
	return p, nil
}

// The row-value comparison (created_at, id) < ($1, $2) means "sorts before the
// cursor row" for the pair. It needs the same direction on both columns, which
// holds here because both are DESC.
const firstPageSQL = `
	SELECT id, customer_id, total_cents, created_at
	FROM orders
	ORDER BY created_at DESC, id DESC
	LIMIT $1`

const nextPageSQL = `
	SELECT id, customer_id, total_cents, created_at
	FROM orders
	WHERE (created_at, id) < ($1, $2)
	ORDER BY created_at DESC, id DESC
	LIMIT $3`

type Page struct {
	Orders     []Order
	NextCursor string // empty when this is the last page
}

// ListOrders returns the page after cursor. An empty cursor means the first page.
// It fetches size+1 rows: the extra row only tells us whether a next page exists.
func ListOrders(ctx context.Context, db *sql.DB, cursor string, size int) (Page, error) {
	if size < 1 {
		size = 20
	}

	var (
		rows *sql.Rows
		err  error
	)
	if cursor == "" {
		rows, err = db.QueryContext(ctx, firstPageSQL, size+1)
	} else {
		p, derr := DecodeCursor(cursor)
		if derr != nil {
			return Page{}, derr
		}
		rows, err = db.QueryContext(ctx, nextPageSQL, p.CreatedAt, p.ID, size+1)
	}
	if err != nil {
		return Page{}, fmt.Errorf("query orders: %w", err)
	}
	defer rows.Close()

	var orders []Order
	for rows.Next() {
		var o Order
		if err := rows.Scan(&o.ID, &o.CustomerID, &o.TotalCents, &o.CreatedAt); err != nil {
			return Page{}, fmt.Errorf("scan order: %w", err)
		}
		orders = append(orders, o)
	}
	if err := rows.Err(); err != nil {
		return Page{}, fmt.Errorf("iterate orders: %w", err)
	}

	page := Page{}
	if len(orders) > size {
		orders = orders[:size]
		next, err := EncodeCursor(orders[size-1])
		if err != nil {
			return Page{}, err
		}
		page.NextCursor = next
	}
	page.Orders = orders
	return page, nil
}

Pass the request's ctx to QueryContext so a client that gives up cancels the query; this matters most for the deep offset queries that are slowest. time.Time marshals with nanoseconds and PostgreSQL stores microseconds, so a time.Time cursor round-trips exactly; format the timestamp with fewer digits and the boundary moves.

Laravel, before (paginate()): COUNT(*) plus offset on every request.

php
<?php

namespace App\Http\Controllers\Orders;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\JsonResponse;

final class OrderIndexController extends Controller
{
    // Offset pagination. paginate() first runs SELECT COUNT(*) over the whole
    // filtered set, then SELECT ... ORDER BY ... LIMIT 50 OFFSET (page - 1) * 50.
    // On a large orders table both queries get slower as the page number grows,
    // and rows inserted while a user is reading shift later pages.
    public function __invoke(): JsonResponse
    {
        $orders = Order::query()
            ->where('status', 'paid')
            ->orderByDesc('created_at')
            ->orderByDesc('id')
            ->paginate(50);

        return response()->json($orders);
    }
}

Laravel, after: cursorPaginate() for the standard case; a hand-rolled controller when you must own the cursor format.

php
<?php

// Index this for both actions below:
//   CREATE INDEX orders_paid_feed ON orders (status, created_at, id);

namespace App\Http\Controllers\Orders;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class OrderFeedController extends Controller
{
    private const PER_PAGE = 50;

    // (1) The standard case. cursorPaginate() reads the order columns, builds the
    // "after the last row" WHERE clause itself, and emits Next/Previous cursors.
    // The order must be unique: created_at alone is not, so id is the tie-breaker.
    public function index(): JsonResponse
    {
        $orders = Order::query()
            ->where('status', 'paid')
            ->orderByDesc('created_at')
            ->orderByDesc('id')
            ->cursorPaginate(self::PER_PAGE);

        return response()->json($orders);
    }

    // (2) Hand-rolled keyset with the query builder. Use it when you must own the
    // cursor format (versioning, signing, a public API contract) or when the
    // paginator's rules do not fit the query. It expands (created_at, id) < (c, i)
    // into OR-ed conditions. MySQL accepts row values, but its optimizer may use
    // only the index prefix for them (MySQL 8.4 manual, row constructor
    // optimization), so the OR form is the safe one there.
    public function feed(Request $request): JsonResponse
    {
        $query = Order::query()
            ->select(['id', 'customer_id', 'total_cents', 'created_at'])
            ->where('status', 'paid');

        $cursor = $this->decodeCursor($request->query('cursor'));

        if ($cursor !== null) {
            $query->where(function (Builder $q) use ($cursor): void {
                $q->where('created_at', '<', $cursor['c'])
                    ->orWhere(function (Builder $q) use ($cursor): void {
                        $q->where('created_at', '=', $cursor['c'])
                            ->where('id', '<', $cursor['i']);
                    });
            });
        }

        // Fetch one row more than the page size. The extra row only tells us
        // whether another page exists.
        $rows = $query
            ->orderByDesc('created_at')
            ->orderByDesc('id')
            ->limit(self::PER_PAGE + 1)
            ->get();

        $page = $rows->take(self::PER_PAGE);
        $next = null;

        if ($rows->count() > self::PER_PAGE) {
            $last = $page->last();

            // getRawOriginal() returns the database string with its microseconds.
            // Formatting the Carbon instance would drop them and make rows
            // sharing the same second get skipped or repeated.
            $next = $this->encodeCursor($last->getRawOriginal('created_at'), $last->id);
        }

        return response()->json([
            'data' => $page,
            'next_cursor' => $next,
        ]);
    }

    /** @return array{c: string, i: int}|null */
    private function decodeCursor(?string $raw): ?array
    {
        if ($raw === null || $raw === '') {
            return null;
        }

        try {
            $data = json_decode(
                (string) base64_decode(strtr($raw, '-_', '+/')),
                true,
                4,
                JSON_THROW_ON_ERROR,
            );
        } catch (\JsonException) {
            abort(422, 'Invalid cursor.');
        }

        if (! is_array($data) || ! is_string($data['c'] ?? null) || ! is_int($data['i'] ?? null)) {
            abort(422, 'Invalid cursor.');
        }

        return $data;
    }

    private function encodeCursor(string $createdAt, int $id): string
    {
        $json = json_encode(['c' => $createdAt, 'i' => $id], JSON_THROW_ON_ERROR);

        return rtrim(strtr(base64_encode($json), '+/', '-_'), '=');
    }
}

Previous page (backward paging) ​

sql
-- page forward:  WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 51
-- page backward: flip operator and order, then reverse the rows in the application
SELECT * FROM (
    SELECT id, created_at FROM orders
    WHERE (created_at, id) > ($1, $2)          -- cursor = FIRST row of the current page
    ORDER BY created_at ASC, id ASC
    LIMIT 51
) t
ORDER BY created_at DESC, id DESC;

Relay spells the same thing last/before. Laravel stores the direction in the cursor as _pointsToNextItems.

A signed, versioned, expiring cursor ​

The Go codec verifies the signature first (constant time), then the version, expiry and filter fingerprint. The PHP class does the same with hash_hmac and hash_equals.

go
// Package signed shows a production-shaped keyset cursor: versioned, signed with
// HMAC-SHA256, bound to the query it was issued for, and expiring. Base64 only
// makes a cursor URL-safe; the signature is what stops a client from editing it.
package signed

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"errors"
	"strings"
	"time"
)

// Version is bumped whenever the payload shape or the sort order changes.
// Old cursors then fail cleanly instead of producing a wrong boundary.
const Version = 1

var (
	ErrMalformed   = errors.New("cursor malformed")
	ErrBadSig      = errors.New("cursor signature mismatch")
	ErrExpired     = errors.New("cursor expired")
	ErrVersion     = errors.New("cursor version unsupported")
	ErrWrongFilter = errors.New("cursor issued for a different query")
)

// Payload is what the server needs to resume: the sort key of the last row, a
// fingerprint of the filter and sort, and an expiry.
type Payload struct {
	V   int       `json:"v"`
	At  time.Time `json:"c"`   // last row created_at
	ID  int64     `json:"i"`   // last row id (tie-breaker)
	Fp  string    `json:"f"`   // fingerprint of filter + sort
	Exp int64     `json:"exp"` // unix seconds
}

// Codec holds the secret. Keep the key in config, not in the repository, and
// rotate it by accepting an old key for as long as the cursor TTL.
type Codec struct {
	Key []byte
	TTL time.Duration
	Now func() time.Time
}

func (c Codec) now() time.Time {
	if c.Now != nil {
		return c.Now()
	}
	return time.Now()
}

func (c Codec) mac(body string) []byte {
	m := hmac.New(sha256.New, c.Key)
	m.Write([]byte(body))
	return m.Sum(nil)
}

// Fingerprint turns the filter and sort into a short stable string. Two
// requests with different filters must never share a cursor.
func Fingerprint(parts ...string) string {
	h := sha256.Sum256([]byte(strings.Join(parts, "\x1f")))
	return base64.RawURLEncoding.EncodeToString(h[:6])
}

// Encode returns "<body>.<signature>", both base64url without padding.
func (c Codec) Encode(at time.Time, id int64, fp string) (string, error) {
	p := Payload{V: Version, At: at, ID: id, Fp: fp, Exp: c.now().Add(c.TTL).Unix()}
	raw, err := json.Marshal(p)
	if err != nil {
		return "", err
	}
	body := base64.RawURLEncoding.EncodeToString(raw)
	sig := base64.RawURLEncoding.EncodeToString(c.mac(body))
	return body + "." + sig, nil
}

// Decode verifies the signature first (constant time), then the version, the
// expiry and the fingerprint. Only then is the payload trusted as a boundary.
func (c Codec) Decode(token, wantFp string) (Payload, error) {
	body, sig, ok := strings.Cut(token, ".")
	if !ok {
		return Payload{}, ErrMalformed
	}
	got, err := base64.RawURLEncoding.DecodeString(sig)
	if err != nil {
		return Payload{}, ErrMalformed
	}
	if !hmac.Equal(got, c.mac(body)) {
		return Payload{}, ErrBadSig
	}
	raw, err := base64.RawURLEncoding.DecodeString(body)
	if err != nil {
		return Payload{}, ErrMalformed
	}
	var p Payload
	if err := json.Unmarshal(raw, &p); err != nil {
		return Payload{}, ErrMalformed
	}
	switch {
	case p.V != Version:
		return Payload{}, ErrVersion
	case c.now().Unix() > p.Exp:
		return Payload{}, ErrExpired
	case p.Fp != wantFp:
		return Payload{}, ErrWrongFilter
	}
	return p, nil
}
php
<?php

namespace App\Support;

use Carbon\CarbonImmutable;
use InvalidArgumentException;

/**
 * A versioned, signed, expiring keyset cursor for a hand-rolled API.
 * Laravel's own cursorPaginate() cursor is unsigned base64url JSON; use this
 * class when clients must not be able to edit the boundary or replay a cursor
 * against a different filter.
 */
final class SignedCursor
{
    private const VERSION = 1;

    public function __construct(
        private readonly string $key,
        private readonly int $ttlSeconds = 3600,
    ) {}

    /** Fingerprint of everything that changes the meaning of "after this row". */
    public static function fingerprint(string ...$parts): string
    {
        return substr(hash('sha256', implode("\x1f", $parts)), 0, 12);
    }

    public function encode(string $createdAt, int $id, string $fingerprint): string
    {
        $body = $this->b64(json_encode([
            'v' => self::VERSION,
            'c' => $createdAt,   // raw database string, microseconds kept
            'i' => $id,
            'f' => $fingerprint,
            'exp' => CarbonImmutable::now()->addSeconds($this->ttlSeconds)->getTimestamp(),
        ], JSON_THROW_ON_ERROR));

        return $body . '.' . $this->b64(hash_hmac('sha256', $body, $this->key, true));
    }

    /** @return array{c: string, i: int} */
    public function decode(string $token, string $fingerprint): array
    {
        [$body, $sig] = array_pad(explode('.', $token, 2), 2, '');

        // hash_equals is constant time; never compare signatures with ===.
        if (! hash_equals($this->b64(hash_hmac('sha256', $body, $this->key, true)), $sig)) {
            throw new InvalidArgumentException('bad signature');
        }

        $p = json_decode($this->unb64($body), true, 4, JSON_THROW_ON_ERROR);

        if (($p['v'] ?? null) !== self::VERSION) {
            throw new InvalidArgumentException('unsupported version');
        }
        if (($p['exp'] ?? 0) < CarbonImmutable::now()->getTimestamp()) {
            throw new InvalidArgumentException('expired');
        }
        if (($p['f'] ?? null) !== $fingerprint) {
            throw new InvalidArgumentException('cursor belongs to another query');
        }

        return ['c' => $p['c'], 'i' => $p['i']];
    }

    private function b64(string $raw): string
    {
        return rtrim(strtr(base64_encode($raw), '+/', '-_'), '=');
    }

    private function unb64(string $s): string
    {
        return (string) base64_decode(strtr($s, '-_', '+/'));
    }
}

Use it in a Laravel controller: build the fingerprint from every request input that changes the result (filters and sort), decode the incoming cursor with it, and return 422 on any InvalidArgumentException.

Counts without scanning the table ​

go
// Package count shows the three honest ways to answer "how many?" for a big
// table without a COUNT(*) on every request: a planner estimate, a capped
// exact count ("1000+"), and a short-lived cache.
package count

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"sync"
	"time"
)

// TableEstimate reads pg_class.reltuples, the planner's row estimate for the
// whole table. It is -1 on PostgreSQL 14+ when the table was never vacuumed or
// analyzed, so callers must treat negative values as "unknown".
func TableEstimate(ctx context.Context, db *sql.DB, table string) (int64, error) {
	var n float64
	err := db.QueryRowContext(ctx,
		`SELECT reltuples FROM pg_class WHERE oid = $1::regclass`, table).Scan(&n)
	if err != nil {
		return 0, fmt.Errorf("reltuples: %w", err)
	}
	return int64(n), nil
}

// QueryEstimate asks the planner how many rows a filtered query would return,
// using EXPLAIN (FORMAT JSON). Nothing is executed. The statement text must be
// built by trusted code; only values go through args.
func QueryEstimate(ctx context.Context, db *sql.DB, stmt string, args ...any) (int64, error) {
	var raw []byte
	if err := db.QueryRowContext(ctx, "EXPLAIN (FORMAT JSON) "+stmt, args...).Scan(&raw); err != nil {
		return 0, fmt.Errorf("explain: %w", err)
	}
	var plans []struct {
		Plan struct {
			PlanRows float64 `json:"Plan Rows"`
		} `json:"Plan"`
	}
	if err := json.Unmarshal(raw, &plans); err != nil || len(plans) == 0 {
		return 0, fmt.Errorf("explain json: %v", err)
	}
	return int64(plans[0].Plan.PlanRows), nil
}

// CappedCount counts at most limit+1 rows, so the cost is bounded by limit no
// matter how big the table is. If exact is false the UI shows "limit+".
func CappedCount(ctx context.Context, db *sql.DB, status string, limit int) (n int, exact bool, err error) {
	err = db.QueryRowContext(ctx, `
		SELECT count(*) FROM (
			SELECT 1 FROM orders WHERE status = $1 LIMIT $2
		) t`, status, limit+1).Scan(&n)
	if err != nil {
		return 0, false, err
	}
	if n > limit {
		return limit, false, nil
	}
	return n, true, nil
}

// Cache keeps one count per filter key for a short TTL. Stale by design: a
// page total that is 30 seconds old is fine; a COUNT(*) per request is not.
type Cache struct {
	mu  sync.Mutex
	ttl time.Duration
	m   map[string]entry
}

type entry struct {
	n    int64
	when time.Time
}

func NewCache(ttl time.Duration) *Cache {
	return &Cache{ttl: ttl, m: make(map[string]entry)}
}

// Get returns the cached count or calls load and stores the result.
func (c *Cache) Get(key string, load func() (int64, error)) (int64, error) {
	c.mu.Lock()
	e, ok := c.m[key]
	c.mu.Unlock()
	if ok && time.Since(e.when) < c.ttl {
		return e.n, nil
	}
	n, err := load()
	if err != nil {
		return 0, err
	}
	c.mu.Lock()
	c.m[key] = entry{n: n, when: time.Now()}
	c.mu.Unlock()
	return n, nil
}
php
// Laravel: a cached, capped count next to a simplePaginate()
$total = Cache::remember(
    'orders:paid:count',
    now()->addSeconds(30),
    fn () => DB::table('orders')->where('status', 'paid')->limit(10001)->count(),
);
// $total is 10001 when there are more than 10,000 rows: show "10,000+"

Note that ->limit(10001)->count() is not capped in SQL: count() wraps the query as an aggregate and the LIMIT applies to the single result row. For a real cap, use a subquery: DB::query()->fromSub(DB::table('orders')->where('status','paid')->select('id')->limit(10001), 't')->count().

The MySQL deferred join in Laravel ​

php
<?php

namespace App\Http\Controllers\Orders;

use App\Models\Order;
use Illuminate\Support\Facades\DB;

// Deferred join: keep OFFSET (you need page numbers) but make the database
// skip over narrow index entries instead of wide rows. The inner query reads
// only ids from an index; the outer query fetches full rows for 50 ids.
//
//   CREATE INDEX orders_paid_feed ON orders (status, created_at, id);
final class DeferredJoinPage
{
    public function page(int $page, int $perPage = 50)
    {
        $ids = DB::table('orders')
            ->select('id')
            ->where('status', 'paid')
            ->orderByDesc('created_at')
            ->orderByDesc('id')
            ->offset(($page - 1) * $perPage)
            ->limit($perPage);

        return Order::query()
            ->joinSub($ids, 'page', fn ($join) => $join->on('orders.id', '=', 'page.id'))
            ->orderByDesc('orders.created_at')
            ->orderByDesc('orders.id')
            ->get('orders.*');
    }
}

Export or walk every row ​

php
// Eloquent: keyset under the hood, safe while updating the filter column
Order::where('status', 'pending')->chunkById(1000, function ($orders) {
    foreach ($orders as $order) {
        $order->update(['status' => 'queued']);   // chunk() would skip rows here
    }
});

// one row at a time, still keyset
foreach (Order::where('status', 'pending')->lazyById(1000) as $order) {
    // ...
}

The Go version is the keyset loop in the Go section. For one consistent snapshot of a very large table, use a server-side cursor inside a REPEATABLE READ transaction (isolation levels, cursors & streaming).

Failure handling and client rules ​

SituationServerClient
Invalid, expired or mismatched cursor400 with a stable codeDo not retry; restart from page 1
Query timeout on a deep pagestatement_timeout, 503Retry with backoff; keyset avoids it
Duplicate across pages (offset APIs)Cannot be preventedDe-duplicate by id on the client
Short pageMay happen (Slack, DynamoDB filters)Stop only on the end marker, never on page size
Rate limit429 + Retry-AfterBack off, cap depth
Delete of the cursor rowFine for keysetContinue

Choosing a method ​

WorkloadRecommendationExtra techniqueReason
Social feed, activity stream, notificationsKeyset, signed cursorhas_more flag, no totalsHeavy writes, infinite scroll
Public REST APIKeyset cursor in the body or Link headerVersion and expire cursors, limit capStable, forward-only
GraphQLRelay connectionsfirst/after, opaque cursorsThe spec and client libraries expect it
Admin table over a small table (under about 10,000 rows)paginate() offsetIndex on the sort columnNumbered pages are worth it
Admin table over millions of rowsKeyset plus filters, or search engineDepth cap, estimated countUsers filter instead of paging
Numbered pager on a big tableHybrid bookmarks, or cap at N pagesEstimated totalPage numbers with bounded offset
MySQL, wide rows, must keep offsetDeferred joinCovering indexCheaper skip
Exports, ETL, backfillschunkById / keyset loopBatch size 500-5,000Resumable, safe under updates
Search resultssearch_after + PIT (Elasticsearch)Tiebreakerfrom/size capped at 10,000
DynamoDBLastEvaluatedKeyDo not filter after readingNo other option
MongoDBRange on _id or compound keyInclude _id in the sortskip scans

In architecture: from a single process to a distributed system ​

Pagination is an API contract, so the decision is made at the boundary, not in the query. A numbered pager with totals means offset, a count and a page parameter that clients may rely on. An infinite feed means keyset, an opaque cursor and no totals. Mixing the two in one endpoint is common and confusing.

Monolith: one process, one database ​

How it shows up: a controller calls paginate() and a Blade or Inertia view renders page links. It is correct while the table is small.

Simplest correct usage: keep paginate() for admin grids on small tables; use cursorPaginate() or simplePaginate() the moment a list is public or grows; always add a unique tie-breaker to orderBy.

Example (simple): an internal "customers" grid with 8,000 rows, paginate(25), an index on name. Nothing to fix.

Example (complex): the customer-facing "orders" feed grows to 40 million rows, with an export job running at night. The feed moves to cursorPaginate() with (status, created_at, id) indexed; the export uses chunkById(2000); the order count in the header comes from Cache::remember with a 30 s TTL.

Modular monolith and multiple databases ​

Each module owns its table and its cursor format; modules expose list(after: Cursor, limit) rather than page(n), so a module can change its storage without changing callers. A cross-module list (an "activity" page combining orders, invoices and shipments) cannot be a single ORDER BY; either each module paginates itself and the page merges, or a read-model table (an "activity feed" projection) holds one sortable key for all of them, which is just a denormalised sort key on one table.

Microservices: composite cursors and fan-out ​

What survives: the contract (limit, cursor, next_cursor, has_more). What does not: a single ORDER BY across services.

text
     Client            API gateway / BFF                Orders svc            Invoices svc
1    GET /activity?limit=20
2                      -> GET /orders?limit=20          returns 20 + oc1
3                      -> GET /invoices?limit=20                              returns 20 + ic1
4                      merge by created_at desc, keep 20
5                      cursor = {orders: oc_x, invoices: ic_y}   signed, versioned
6    <- 20 items + next_cursor

The gateway's cursor is a vector of per-service cursors; each service's own cursor stays opaque to the gateway (the Relay rule applied recursively). Each page asks every service for limit rows (the merge may consume all of one service's rows), so fan-out cost is services x limit. The merged order is only as stable as the least stable service, and a service that changes its cursor format breaks gateway cursors, which is why every cursor carries a version and an expiry.

Distributed data: replicas, caches and sharding ​

Replicas. Offset pages across replicas with different lag duplicate or skip rows (above); keyset is safe because the boundary value means the same thing everywhere. Pin a session to one replica when a write was just made.

Caches. Cache a page by (filter fingerprint, cursor), not by page number; the same cursor always means the same boundary. A cached page goes stale when a newer row appears above the boundary, which is what the first page's short TTL (or a purge on write) fixes. Cache counts separately with a longer TTL.

Sharded and distributed SQL. A deep offset across shards means each shard returns offset + limit rows to the coordinator, which sorts and discards: the cost multiplies by the shard count. This is Elasticsearch's 10,000-hit wall, and CockroachDB and Citus pay a version of it too. Keyset across shards: each shard returns limit rows after the cursor and the coordinator does a k-way merge; the cursor is the global sort key. See Partitioning & Sharding in PostgreSQL and Distributed SQL.

Multi-region. A cursor issued by one region may hit a replica in another that has not yet seen the row; the range predicate still works, which is another reason cursors hold values and not row identities.

Scaling path: 1x, 10x, 100x ​

ScaleRows in the paged tableWhat to do
1xUnder 10,000paginate() is fine; add the index on the sort column
10xHundreds of thousandsSwitch public lists to cursorPaginate() or simplePaginate(); drop exact totals; cache the count
100xTens of millions and upKeyset everywhere; signed, versioned cursors; estimated or capped counts; partial or covering indexes per hot filter; exports via chunkById on a replica; consider a search engine for arbitrary filters and sorts
1000xBillions, shardedPer-shard cursors with k-way merge, time-based partitioning with the partition key in the cursor (Billion-row tables), pre-computed read models

Lab ​

Two terminals (psql as session A and session B). The plan outputs in comments are the expected shape; timings depend on your machine, and you should see the actual rows ratio (900,050 against 50) on any hardware.

Setup: one million rows, with ties on purpose.

bash
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
docker exec -it pg psql -U postgres
sql
CREATE TABLE orders (
    id          bigserial PRIMARY KEY,
    customer_id bigint      NOT NULL,
    status      text        NOT NULL,
    total_cents bigint      NOT NULL,
    created_at  timestamptz NOT NULL
);

-- three rows per second: ties are guaranteed
INSERT INTO orders (customer_id, status, total_cents, created_at)
SELECT (random() * 50000)::int,
       (ARRAY['paid','pending','refunded'])[1 + (random() * 2)::int],
       (random() * 100000)::int,
       now() - ((g / 3) * interval '1 second')
FROM generate_series(1, 1000000) AS g;

CREATE INDEX orders_feed ON orders (created_at DESC, id DESC);
ANALYZE orders;

Experiment 1: OFFSET 900000 against keyset.

sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, customer_id, total_cents, created_at FROM orders
ORDER BY created_at DESC, id DESC LIMIT 50 OFFSET 900000;
-- Limit (actual rows=50)
--   -> Index Scan using orders_feed on orders (actual rows=900050)   <- the 900,000 discarded rows
-- Execution time: hundreds of ms to seconds, Buffers: very large

-- take the last row of that page and seek to it
SELECT created_at, id FROM orders ORDER BY created_at DESC, id DESC OFFSET 900049 LIMIT 1;  -- remember both values

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, customer_id, total_cents, created_at FROM orders
WHERE (created_at, id) < ('<created_at from above>', <id from above>)
ORDER BY created_at DESC, id DESC LIMIT 50;
-- Limit (actual rows=50)
--   -> Index Scan using orders_feed on orders (actual rows=50)
--        Index Cond: (ROW(created_at, id) < ROW(...))
-- Execution time: well under a millisecond or two, Buffers: a handful

Experiment 2: duplicates under concurrent inserts (offset).

sql
-- session A
CREATE TABLE feed (id serial PRIMARY KEY, n int);
INSERT INTO feed (n) SELECT g FROM generate_series(1, 9) g;
SELECT id FROM feed ORDER BY id DESC LIMIT 3 OFFSET 0;   -- 9, 8, 7

-- session B
INSERT INTO feed (n) VALUES (10);                        -- id 10, newest

-- session A, "page 2"
SELECT id FROM feed ORDER BY id DESC LIMIT 3 OFFSET 3;   -- 7, 6, 5   <- 7 appeared twice

-- same thing with keyset from the last row of page 1 (id 7)
SELECT id FROM feed WHERE id < 7 ORDER BY id DESC LIMIT 3;   -- 6, 5, 4   no duplicate

Experiment 3: ties without a tie-breaker lose rows.

sql
-- cursor on created_at alone: take the third row of the tie group
SELECT created_at FROM orders ORDER BY created_at DESC LIMIT 1 OFFSET 1;
SELECT count(*) FROM orders
WHERE created_at = (SELECT created_at FROM orders ORDER BY created_at DESC LIMIT 1 OFFSET 1);   -- 3 rows share it
-- page 1 of size 2 ended inside the group; WHERE created_at < that value drops the rest of the group
-- with (created_at, id) the third row is returned

Experiment 4: NULL in the cursor drops pages.

sql
ALTER TABLE orders ADD COLUMN shipped_at timestamptz;
UPDATE orders SET shipped_at = created_at + interval '1 day' WHERE id % 2 = 0;
SELECT count(*) FROM orders WHERE (shipped_at, id) > (NULL, 40);   -- 0: unknown for every row
SELECT count(*) FROM orders WHERE shipped_at IS NULL AND id > 40;  -- the correct "NULL region" query

Experiment 5: exact against estimated counts.

sql
SELECT count(*) FROM orders WHERE status = 'paid';                       -- exact, scans
SELECT reltuples::bigint FROM pg_class WHERE oid = 'orders'::regclass;   -- ~1000000, instant
EXPLAIN (FORMAT JSON) SELECT 1 FROM orders WHERE status = 'paid';        -- "Plan Rows": about a third
INSERT INTO orders (customer_id, status, total_cents, created_at)
SELECT 1, 'paid', 1, now() FROM generate_series(1, 100000);
SELECT reltuples::bigint FROM pg_class WHERE oid = 'orders'::regclass;   -- unchanged until autovacuum/ANALYZE

Experiment 6: the SQL cursorPaginate() really runs (Laravel, php artisan tinker).

php
use Illuminate\Pagination\Cursor;
use Illuminate\Support\Facades\DB;
use App\Models\Order;

// (a) a builder you control: toRawSql() shows the OR-expanded hand-rolled form
Order::where('status', 'paid')
    ->where(fn ($q) => $q->where('created_at', '<', '2026-11-25 10:00:00')
        ->orWhere(fn ($q) => $q->where('created_at', '2026-11-25 10:00:00')->where('id', '<', 8)))
    ->orderByDesc('created_at')->orderByDesc('id')->limit(51)->toRawSql();

// (b) the paginator builds its condition inside cursorPaginate(), so log the real query
DB::enableQueryLog();
Order::where('status', 'paid')->orderByDesc('created_at')->orderByDesc('id')
    ->cursorPaginate(50, ['*'], 'cursor', new Cursor(['created_at' => '2026-11-25 10:00:00', 'id' => 8], true));
DB::getRawQueryLog();
// select * from "orders" where "status" = 'paid'
//   and ("created_at" < '2026-11-25 10:00:00' or ("created_at" = '2026-11-25 10:00:00' and ("id" < 8)))
//   order by "created_at" desc, "id" desc limit 51
// (expected shape derived from BuildsQueries::paginateUsingCursor, see the references)

Common misconceptions ​

BeliefReality
"An index makes OFFSET fast"It removes the sort, not the walk: the skipped rows are still produced
"LIMIT 50 means the query is cheap"Cost is the rows produced, not the rows returned
"ORDER BY created_at is deterministic"Only if unique; ties come back in plan-dependent order (the MySQL manual says so explicitly)
"Base64 hides or protects the cursor"It is an encoding; sign it (HMAC) to prevent edits, encrypt only if values are secret
"(a, b) < (x, y) means a < x AND b < y"It is lexicographic; the same operator for both columns, so mixed ASC/DESC needs the expanded form
"Keyset can jump to page 40"No: there is no key for "page 40" without reading the rows before it
"COUNT(*) is free"It scans (MVCC, InnoDB); use estimates, caps or a cache
"A short page means the last page"Not in Slack, DynamoDB with filters, or any API that may return fewer rows; use the end marker
"NULLs sort somewhere, so the cursor works"Row comparison with NULL is unknown, and WHERE drops those rows
"chunk() and chunkById() are the same"chunk() is offset and skips rows when the loop changes the filter column
"Cursors are valid for ever"A sort or index change makes old cursors wrong; version and expire them
"Deferred join fixes pagination"It makes the offset cheaper, not stable; page numbers still drift

Cheat sheet ​

TopicWhat to remember
Offset costOFFSET m produces and discards m rows; cost grows with the page number
Offset driftPositions move: inserts cause duplicates, deletes cause gaps
Seek conditionWHERE (a, b) < ($1, $2) for ORDER BY a DESC, b DESC
Tie-breakerAlways end ORDER BY with a unique column, same direction, same index
Mixed orderRow values cannot do it: a < $1 OR (a = $1 AND b > $2), or the redundant a <= $1 trick
MySQLPrefer the expanded OR; check key_len; ties are plan-dependent
NULLsRow comparison with NULL is unknown: NOT NULL, a sentinel or a two-region cursor
CursorOpaque, versioned, expiring, HMAC-signed, bound to the filter fingerprint
n + 1Fetch limit + 1 rows; the extra row is has_more
Countspg_class.reltuples, EXPLAIN Plan Rows, capped LIMIT 1001, cached; or drop the total
Page NKeyset cannot; use a depth cap, bookmarks or a filter
ReplicasKeyset tolerates lag; offset across replicas duplicates; pin sessions
Laravelpaginate = count + offset; simplePaginate = offset only; cursorPaginate = keyset (unsigned cursor)
Walking a tablechunkById / lazyById, not chunk()
APIsStripe starting_after, Slack next_cursor, Relay pageInfo, GitHub Link, DynamoDB LastEvaluatedKey, ES search_after
End of dataTrust the end marker, never a short page

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does an index on created_at not make OFFSET 900000 fast? Must-know ​

Answer

Answer: The index removes the sort, but the executor still walks 900,000 entries (and, unless the index covers the query, fetches 900,000 heap tuples) before returning 50. The cost is in rows produced, not rows returned.

2 — A feed shows the same order twice across pages 1 and 2. What happened and what fixes it? Must-know ​

Answer

Answer: A row was inserted above the reader, so every later position shifted by one (offset drift). Keyset pagination fixes it because the boundary is the last row's key, which does not move.

3 — Why must the ORDER BY end with a unique column? Must-know ​

Answer

Answer: Rows with equal sort values come back in any order, differing between executions (the PostgreSQL and MySQL manuals both say so), and a page boundary inside a tie group loses or repeats rows. The unique tie-breaker makes the order total.

4 — What does (a, b) < (x, y) mean, and when can you not use it? Important ​

Answer

Answer: Lexicographic: a < x OR (a = x AND b < y). It applies one operator to every pair, so it cannot express mixed ASC/DESC; it gives unknown with NULLs; and MySQL, SQL Server and Oracle need the expanded form to use the index fully.

5 — Write the seek condition for ORDER BY created_at DESC, id ASC. Must-know ​

Answer

Answer: created_at < $1 OR (created_at = $1 AND id > $2), ideally with the redundant created_at <= $1 and an index on (created_at DESC, id ASC).

6 — Why is base64 not enough for a cursor, and what does a signature add? Important ​

Answer

Answer: Base64 is reversible and editable. An HMAC over the body with a server secret makes any edit detectable; add a version, expiry and filter fingerprint so old or replayed cursors fail cleanly.

7 — How do you show "page 3 of 240" on a 40-million-row table cheaply? Good to know ​

Answer

Answer: Use a planner estimate (pg_class.reltuples, EXPLAIN Plan Rows), a capped count ("1000+"), or a cached count with a short TTL; or drop the total.

8 — Why can keyset pagination not jump to page 40, and what are the options? Important ​

Answer

Answer: No key corresponds to "40th page" without reading the preceding rows. Options: cap the depth and use offset, build bookmark keys every N rows (hybrid), or give the user a filter or date jump.

9 — What is a deferred join and what does it not fix? Important ​

Answer

Answer: An inner query that reads only ids from an index applies OFFSET/LIMIT, then joins back for the full rows. It makes the skip cheaper (late row lookup) but the offset still drifts under writes.

10 — Why use chunkById() instead of chunk() when the loop updates the filter column? Must-know ​

Answer

Answer: chunk() uses offset, so rows that stop matching shift later chunks and some are skipped. chunkById() asks for id greater than the last id, so it is unaffected.

11 — How does Slack tell you the list has ended, and what must you not do? Important ​

Answer

Answer: An empty, null or missing next_cursor in response_metadata ends the list. Do not infer the end from a result shorter than limit.

12 — Why is keyset better than offset on read replicas? Important ​

Answer

Answer: The boundary value means the same on any replica regardless of lag, while offset positions differ between replicas at different lag levels, causing duplicates and gaps.

Glossary ​

TermMeaning
PaginationReturning a large result in slices
LIMITMaximum rows returned
OFFSETRows to skip before returning; the database still produces them
FETCH NEXT ... ROWS ONLYSQL-standard spelling of LIMIT (SQL Server, Oracle, PostgreSQL)
Keyset paginationPaging by "after this key" instead of by position
Seek methodWinand's name for keyset pagination
Cursor (API)An opaque token that marks where the last page ended
Server-side cursorA database object (DECLARE/FETCH) that streams rows; not the same as an API cursor
Row value / row constructorA tuple such as (a, b) usable in comparisons
Lexicographic comparisonCompare the first element, then the next only on a tie
Tie-breakerA unique column added to ORDER BY to make it total
Total orderAn ordering where no two rows compare equal
Deterministic orderThe same query always returns rows in the same order
Index CondEXPLAIN line showing a predicate used to seek in the index
Rows Removed by FilterRows read and then discarded by a non-index predicate
Index Only ScanAnswers from the index without heap access (needs the visibility map)
Late row lookupPostponing the clustered-index row fetch until after offset and limit
Deferred joinSQL form of late row lookup: a narrow inner query joined back to the table
filesortMySQL's sort of rows that an index could not order
key_lenMySQL EXPLAIN column: how much of the index key is used
n + 1 fetchRequest one extra row to learn whether a next page exists
has_more / hasNextPageFlag meaning another page exists
Opaque cursorA token the client must not parse or build
base64urlURL-safe base64 alphabet without padding
HMACKeyed hash that proves a message was not altered
Constant-time comparisonComparison whose time does not reveal where bytes differ (hmac.Equal, hash_equals)
Cursor fingerprintHash of filter and sort, bound into the cursor
Cursor expiry (exp)Time after which a cursor is rejected
Cursor version (v)Format number bumped on a breaking change
reltuplespg_class column: planner's row estimate for a table
Plan RowsThe planner's estimated row count in EXPLAIN
Capped countcount(*) over a LIMIT cap+1 subquery
Hybrid paginationKeyset bookmarks plus a small offset
Sparse offsets / bookmarksStored keys of every Nth row
Infinite scrollUI that loads the next page when the user reaches the end
Relay connectionGraphQL list type with edges, node, cursor and pageInfo
pageInfohasNextPage, hasPreviousPage, startCursor, endCursor
starting_after / ending_beforeStripe's cursor parameters (object IDs)
next_cursorSlack's cursor field in response_metadata
Link headerRFC 8288 HTTP header carrying next/prev/first/last URLs
search_afterElasticsearch's keyset parameter (sort values of the last hit)
Point in time (PIT)Elasticsearch snapshot of the index for consistent paging
index.max_result_windowElasticsearch limit on from + size (default 10,000)
_shard_docElasticsearch implicit unique tiebreaker under a PIT
LastEvaluatedKey / ExclusiveStartKeyDynamoDB's page marker out and in
skip()MongoDB offset; scans from the start
ObjectIdMongoDB _id default; roughly time-ordered, not strictly monotonic
paginate()Laravel offset pagination with a count
simplePaginate()Laravel offset pagination without a count (perPage + 1)
cursorPaginate()Laravel keyset pagination; unsigned base64url JSON cursor
chunkById() / lazyById()Laravel keyset iteration over a table
toRawSql()Laravel builder method returning SQL with bindings substituted
hot_standby_feedbackPostgreSQL standby setting that stops the primary vacuuming rows a standby query still needs
max_standby_streaming_delayHow long a standby delays WAL replay for a conflicting query
Sticky connectionLaravel option to read from the primary after a write in the same request

References ​

Built by Morteza Negahi