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;| id | title | total |
|---|---|---|
| 8 | h | 8 |
| 7 | g | 8 |
| 6 | f | 8 |
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;| id | title |
|---|---|
| 8 | h |
| 7 | g |
| 6 | f |
| 5 | e |
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