Keyset Pagination Seek Method

Paginate with the seek method on a compound cursor, comparing plans against OFFSET to show why deep pages stay fast.

SqlData Fetching

Code

sqlsnippet
28 lines
-- 键集分页:锚点条件让索引直接定位下一页
SELECT id, created_at, title
FROM articles
WHERE (created_at, id) < ('2026-10-21 14:30:00', 98765)
ORDER BY created_at DESC, id DESC
LIMIT 20;

-- 对照的 OFFSET 版本:深页要扫过全部前序行
SELECT id, created_at, title
FROM articles
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 100000;

-- 首页请求(无锚点)
SELECT id, created_at, title
FROM articles
ORDER BY created_at DESC, id DESC
LIMIT 20;

-- 配套复合索引:排序方向与查询一致
CREATE INDEX idx_articles_page
  ON articles (created_at DESC, id DESC);

-- 验证两种方案的代价差异
EXPLAIN ANALYZE
SELECT id FROM articles
WHERE (created_at, id) < ('2026-10-21 14:30:00', 98765)
ORDER BY created_at DESC, id DESC LIMIT 20;

What the code does

The file runs SELECT / CREATE / EXPLAIN statements, touching articles.

In terms of clauses, the statements use: a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.

Applying it

Run the statement against the articles table; the LIMIT keeps the probe cheap while you tune the predicates.

Statements that matter

SELECT id, created_at, title
FROM articles
WHERE (created_at, id) < ('2026-10-21 14:30:00', 98765)
ORDER BY created_at DESC, id DESC
LIMIT 20;
EXPLAIN ANALYZE
SELECT id FROM articles
WHERE (created_at, id) < ('2026-10-21 14:30:00', 98765)
ORDER BY created_at DESC, id DESC LIMIT 20;
SELECT id, created_at, title
FROM articles
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 100000;

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`articles`.