Keyset Pagination Seek Method
Paginate with the seek method on a compound cursor, comparing plans against OFFSET to show why deep pages stay fast.
Code
-- 键集分页:锚点条件让索引直接定位下一页
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What relations does the SQL touch?
- `articles`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.