Video in progress
To show "Total: 12,345,678 results" on a big table, `COUNT(*)` takes seconds on every page. How do you fix it?
In Postgres, COUNT(*) really counts the matching rows because of MVCC, and on a big table that won't be fast. Usually you don't need the exact number: an estimate from statistics or EXPLAIN, a "1000+" cap, LIMIT n+1 for "is there a next page", or a counter maintained ahead of time is enough.
📖 Answer
The slowness of COUNT(*) in Postgres isn't a bug. Each transaction sees its own snapshot, so the table can't keep one ready-made number; the rows have to be visited (with an index-only scan, in the good case). With a filtered query it's even more expensive.
First I talk to the product side: does the user need the exact "12,345,678"? Almost never.
- An estimate for the whole table.
SELECT reltuples::bigint FROM pg_class WHERE oid = 'orders'::regclass;
ANALYZE/autovacuum keeps it updated, and the error is usually a few percent.
-
For a filtered query, the planner's estimate.
Plan RowsinEXPLAIN (FORMAT JSON) SELECT .... Sometimes it's quite rough, so the UI shows "~12M". -
A bounded count.
SELECT count(*) FROM (
SELECT 1 FROM orders WHERE status = 'NEW' LIMIT 1001
) t;
-- if it returns 1001, the UI shows "1000+"
Always fast: at most 1001 rows are read.
-
Don't count at all. For infinite scroll or a "Next" button, ask for
LIMIT 21and say "there's a next page" depending on whether the 21st row exists. -
If you really need an exact number (reports, billing), maintain the counter at write time: a separate
counterstable or RedisINCR, driven by events. Many writes to a single row cause lock contention, so I split the counter across 16 rows and sum them on read. If the number can be a minute late, a background job computes it and puts it in the cache.
Elasticsearch also stops counting exactly after 10,000 by default (track_total_hits), which is the industry's own answer to "do we need the exact number?".
Sign up to mark studied questions and save your progress.