Full answer
Choices:
- Estimate: PostgreSQL keeps
reltuplesinpg_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:
EXPLAINoutput 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