Approximate row count without count(*)

For in-app analytics I need to display a card, that shows the number of rows in a big table.

The obvious query is:

SELECT count(*) FROM table_name;

Because of MVCC, Postgres cannot keep a row counter. Every transaction sees its own snapshot of the table. So our count(*) has to walk the whole table (or the whole of the suitable index, if it can do an index-only scan) and check visibility for each row.

For a huge table the cost of this walk can be significant, especially if the analytics dashboard is periodically refreshed in the browser.

If an approximate count is good enough, we can ask the planner. It keeps its own row estimate in pg_class:

SELECT reltuples::bigint FROM pg_class WHERE oid = 'table_name'::regclass;

On a 3-million-row test table with a warm cache, count(*) took about 150 ms. Querying the planner’s row estimate took well under a millisecond.

How fresh it is

reltuples is updated by VACUUM, ANALYZE, autovacuum and CREATE INDEX. Between those runs it doesn’t move. In the test, after inserting 300k rows and deleting 150k without an analyze, it still said 3,000,028 while the real count was 3,135,000. So use it only for approximate displays, never for exact decisions.

Tables with no statistics

On a table that has never been vacuumed or analyzed, reltuples is -1. Before Postgres 14 it was 0, which may look like a real answer. A freshly created and bulk-loaded table stays at -1 until autovacuum gets to it. Run ANALYZE table_name once, or clamp the value:

SELECT greatest(reltuples, 0)::bigint FROM pg_class WHERE oid = 'table_name'::regclass;

On a real table

Auto-analyze fires whenever the number of rows modified since the last analyze exceeds a threshold: 50 plus 10% of the table size.

Our production table with about 2.6 million rows gets about 300 inserts and 12,000 updates a day.

So auto-analyze runs roughly every three weeks, and reltuples only falls behind by the net inserts in between: about 6,500 rows at worst, or 0.25% of the table.

← All notes