← Back to SQL, page 22

sql-0431 · Medium mid

SELECT COUNT(*) on a 500-million-row table takes minutes, and a dashboard runs it on every page load. How would you fix that?

Exact counts on large tables must scan a table or index, especially in PostgreSQL where MVCC prevents a stored row count. Use an estimate from planner statistics when approximate is fine, maintain a counter table updated by triggers or batch jobs when exact counts are needed, or cache the result for a short time.

Full answer

Choices:

  • Estimate: PostgreSQL keeps reltuples in pg_class, refreshed by VACUUM and ANALYZE. SELECT reltuples::bigint FROM pg_class WHERE relname = 'events' returns instantly and is usually within a few percent.
  • Filtered estimates: EXPLAIN output includes estimated rows for a WHERE clause, which some apps parse for 'about 1.2M results'.
  • Counter table: event_counts(day, n) updated in the same transaction as inserts or by a periodic job. Exact, cheap to read, but adds write work and hot rows if one row is shared.
  • Caching: compute once a minute and serve the cached value.
  • Index-only scans can speed exact counts when the visibility map is current, but still read every index entry.

Most dashboards show '1.2M events' and need no exact count; ask what precision the user needs. These are PostgreSQL behaviours described here, not run.

Key points

  • Exact counts scan data
  • Planner statistics give fast estimates
  • Counter tables give exact cheap reads
  • Cache expensive aggregates
  • Ask what precision is needed

Common mistakes

  • Running COUNT(*) on every request
  • A single global counter row updated by every insert

Follow-ups

  • How accurate is reltuples after a bulk load?
  • How would you count rows per day cheaply?

Tips

  • Ask whether an estimate is acceptable