Video in progress

Why is `SELECT count(*)` slow on a big table, and how do you quickly get an approximate count?

Because of MVCC, PostgreSQL has to check whether each row is visible, so for an exact count it reads the whole table or index. For places like "about 12 million total" in a UI, pg_class.reltuples or the estimate in EXPLAIN is enough.

📖 Answer

People coming from MySQL MyISAM expect "count(*) should be instant". In PostgreSQL there's no ready-made counter for a table: different transactions at the same time must see different numbers.

At best this is an index-only scan, which also depends on the visibility map. On a table with 100 million rows, several seconds is normal.

An approximate count:

SELECT reltuples::bigint AS approx
FROM pg_class
WHERE oid = 'orders'::regclass;

VACUUM and ANALYZE update this value. If you need an estimate with a filter, you can write a small function that reads rows= from EXPLAIN.

Practical solutions:

  • UI pagination. Instead of "1-20 / 12,345,678", show "there is a next page": fetching one extra row with LIMIT 21 is enough.
  • Dashboard. Keep the counter in a separate table or a materialized view and refresh it periodically.
  • An exact count with a filter. Make the query fast with a matching index, for example a partial index for WHERE status = 'NEW'.

Page<T> in Spring Data sends a separate count query for every page. On a big table I return Slice<T>, which doesn't count.