Sphere
Log in Join
☆ 13

Why is COUNT(*) so slow on a 50 million row table?

SELECT COUNT(*) FROM events takes about 40 seconds. The UI only needs an approximate number for a dashboard badge.

⚑ Report

3 replies

☆ 0
P Priya ·2026-11-02#1

Postgres has to visit every row because MVCC means no exact row count is stored. For an approximate value use the reltuples estimate in pg_class.

⚑ Report
☆ 0
D Dan ·2026-11-02#2

Is that estimate accurate enough for a badge?

⚑ Report
☆ 0
M Markus ·2026-11-02#3

Usually within a few percent. For exact numbers on a large table, maintain a counter table or a materialized view refreshed on a schedule.

⚑ Report
Log in to reply.