← Back to SQL, page 13

sql-0249 · Medium mid

A paginated API also needs the total number of matching rows. How can one query return both the page and the total?

Add COUNT(*) OVER () to the SELECT: the window counts all rows that pass WHERE, before LIMIT applies, so each returned row carries the total. It still has to find every matching row, so for very large results consider an estimate, a cached count, or a 'has next page' flag from fetching one extra row.

Full answer
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, created TEXT NOT NULL, title TEXT);
INSERT INTO posts VALUES
  (1,'2026-03-01','a'),(2,'2026-03-02','b'),(3,'2026-03-02','c'),(4,'2026-03-03','d'),
  (5,'2026-03-04','e'),(6,'2026-03-05','f'),(7,'2026-03-05','g'),(8,'2026-03-06','h');
CREATE INDEX posts_created_id ON posts(created, id);
sql
SELECT id, title, COUNT(*) OVER () AS total
FROM posts ORDER BY created DESC, id DESC LIMIT 3;
idtitletotal
8h8
7g8
6f8

The total is 8 even though only 3 rows came back, because window functions are evaluated before LIMIT.

The cheaper alternative when the interface only needs a Next button: ask for one row more than the page size. If 4 rows return for a page of 3, there is a next page; show 3.

sql
SELECT id, title FROM posts ORDER BY created DESC, id DESC LIMIT 4;
idtitle
8h
7g
6f
5e

PostgreSQL can also give a fast estimate from planner statistics (reltuples in pg_class), which suits "about 1.2 million results" labels.

sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, created TEXT NOT NULL, title TEXT);
INSERT INTO posts VALUES
  (1,'2026-03-01','a'),(2,'2026-03-02','b'),(3,'2026-03-02','c'),(4,'2026-03-03','d'),
  (5,'2026-03-04','e'),(6,'2026-03-05','f'),(7,'2026-03-05','g'),(8,'2026-03-06','h');
CREATE INDEX posts_created_id ON posts(created, id);

SELECT id, title, COUNT(*) OVER () AS total
FROM posts ORDER BY created DESC, id DESC LIMIT 3;

SELECT id, title FROM posts ORDER BY created DESC, id DESC LIMIT 4;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • COUNT(*) OVER () returns the total before LIMIT
  • It still scans all matching rows
  • Fetching page size + 1 rows answers 'is there a next page?'
  • Estimates suit very large result sets

Common mistakes

  • Running a separate exact COUNT(*) on every page request for huge tables
  • Expecting LIMIT to reduce the window count

Follow-ups

  • How would you cache counts?
  • What does reltuples represent?

Tips

  • Offer the page size + 1 trick