
Page 1,000 Is Slower Than Page 1: OFFSET vs Keyset Pagination
- كاتب موثّق
محتويات المقال
OFFSET @skip ROWS FETCH NEXT 20 ROWS ONLY, and page 1 is instant. Then a partner's nightly sync starts walking every page, and each request is slower than the last. In a test on SQL Server 2022 with 1,000,000 orders and an index matching the sort, page 1 read 4 pages. Page 10,000 read 958, and the last page, 50,000, read 4,702: every entry of the index, to return 20 rows. The version that selected every column read 613,467 pages for page 10,000, more than twelve times the size of the whole table. The keyset version read 6 pages, whichever page it fetched.
The common misconception
OFFSET 19980 ROWS jumps to row 19,981, so page 1,000 costs the same as page 1.
What actually happens
An index finds values, not positions
OFFSET clause still have to be computed inside the server, so a large OFFSET might be inefficient. In the test's actual plans, the Index Scan under the Top returned 20,000 rows for page 1,000 and 1,000,000 rows for the last page.
Skipped rows pay full price
SELECT * used the same index plus a for the other columns, and the Top sat above the lookups. So page 1,000 looked up 20,000 rows to return 20, and read 61,376 pages; page 10,000 read 613,467. Any join, function or lookup in the query runs for the rows you throw away, too.
Pages drift when the data changes
OFFSET 20 means "skip whatever the first 20 rows are now." In the test, three new orders arrived after page 1 was read, and page 2 began with the last three orders of page 1. Deletes do the opposite and skip rows. Microsoft's ORDER BY docs list the conditions for stable OFFSET paging: the data doesn't change between requests, or every page runs in one snapshot or serializable transaction, and the ORDER BY columns are unique.
Keyset pagination seeks to where you left off
CreatedAt and Id. The next query asks for rows that sort after that row, which an index on (CreatedAt, Id) answers with an and 20 rows of reading. In the test it read 6 pages at page 1,000 and at page 50,000, returned exactly the same rows as OFFSET, and the three new orders didn't move anything, because "after this row" doesn't change when rows are added in front of it.
Remember the last row, not the page number
-- Page N of "newest orders first"SELECT Id, CreatedAt, Status, TotalFROM dbo.OrdersORDER BY CreatedAt DESC, Id DESCOFFSET @skip ROWS FETCH NEXT 20 ROWS ONLY;-- Tested, last page: 1,000,000 rows scanned, 4,702 reads-- Index: (CreatedAt, Id) INCLUDE (Status, Total)-- The client sends back the last row's CreatedAt and IdSELECT TOP (20) Id, CreatedAt, Status, TotalFROM dbo.OrdersWHERE CreatedAt < @lastCreatedAt OR (CreatedAt = @lastCreatedAt AND Id < @lastId)ORDER BY CreatedAt DESC, Id DESC;-- Tested, any page: Index Seek, 6 readsOR spells out "sorts after the last row" one column at a time. SQL Server turned it into a seek on two ranges of the index. It has no shorter form: in the test, (CreatedAt, Id) < (@c, @id) was a syntax error. PostgreSQL supports that row-value comparison, comparing the pairs left to right, and Use The Index, Luke notes that it can use it to access the index:
-- PostgreSQL, with an index on (created_at, id)SELECT id, created_at, status, totalFROM ordersWHERE (created_at, id) < ($1, $2)ORDER BY created_at DESC, id DESCLIMIT 20;OFFSET / FETCH | ||
|---|---|---|
SELECT * | ||
ORDER BY | ORDER BY and an index that matches it |
How to apply it in your project
Find the deep pages Look for large OFFSETvalues, orSkipin LINQ, in logs and in Query Store orpg_stat_statements. Sync jobs and exports that walk every page are the worst case, because each request costs more than the one before.Make the order unique and index it End the ORDER BYwith a unique column, and build a composite index with the same columns in the same order, plusINCLUDEfor what the page returns.Switch the API to a cursor Return the last row's keys as a token, and turn the next request into a WHEREon those keys. EF Core's pagination docs show the same pattern in LINQ.Keep OFFSET where it's cheap Numbered pages over a small or well-filtered result are fine. Cap how deep a page number can go, or use keyset for next and previous and OFFSETonly for jumps, as the EF Core docs suggest.
Key takeaways
OFFSETreads and discards every skipped row: 4 reads for page 1, 4,702 for page 50,000 in the test.Skipped rows pay for everything under the Top, including key lookups: 613,467 reads for page 10,000 with SELECT *.OFFSETpages shift when rows are inserted or deleted between requests.Keyset pagination seeks past the last row seen: 6 reads at any depth in the test, with stable pages. Both methods need a unique ORDER BY; keyset also needs an index that matches it, and gives up random page access.
التعليقات (0)