Offset Pagination Count Window

Implement classic offset pagination with a single-pass window count, page metadata, and sane caps on depth and page size.

SqlData Fetching

Code

sqlsnippet
29 lines
-- 单次往返:数据页与总数用窗口函数一并取回
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: WHERE first, 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

FAQ

Which tables does this file reference?
`customers`.