Offset Pagination Count Window
Implement classic offset pagination with a single-pass window count, page metadata, and sane caps on depth and page size.
Code
-- 单次往返:数据页与总数用窗口函数一并取回
SELECT
id,
name,
email,
status,
COUNT(*) OVER () AS total_matching
FROM customers
WHERE status = 'active'
ORDER BY created_at DESC, id DESC
LIMIT 25 OFFSET 50;
-- 分页参数带硬上限(防恶意大页与深翻页)
-- 应用层生成的 SQL 遵循:
-- page_size <= 100
-- page_number * page_size <= 10000
SELECT id, name
FROM customers
ORDER BY id
LIMIT 100 OFFSET 0;
-- 跳转特定页(第 4 页,每页 25 条)
SELECT
id, name,
COUNT(*) OVER () AS total,
(COUNT(*) OVER () + 24) / 25 AS total_pages
FROM customers
ORDER BY id
LIMIT 25 OFFSET 75;How the snippet works
The file runs SELECT statements, touching customers.
The pieces that do the work: a WHERE clause restricting which rows the statement reaches; COUNT aggregation; a window function (OVER (…)) working across rows while keeping each row in the result; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.
What to watch for
- Remember the evaluation order:
WHEREfirst, window functions later — filtering on the latter needs another query level.
Applying it
Run the statement against the customers table; the LIMIT keeps the probe cheap while you tune the predicates.
Statements that matter
SELECT
id,
name,
email,
status,
COUNT(*) OVER () AS total_matching
FROM customers
WHERE status = 'active'
ORDER BY created_at DESC, id DESC
LIMIT 25 OFFSET 50;
SELECT
id, name,
COUNT(*) OVER () AS total,
(COUNT(*) OVER () + 24) / 25 AS total_pages
FROM customers
ORDER BY id
LIMIT 25 OFFSET 75;
SELECT id, name
FROM customers
ORDER BY id
LIMIT 100 OFFSET 0;
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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does this file reference?
- `customers`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.