Counting rows without the full scan

Back to list2025-07-02
You

Is there a fast approximate count for a huge table?

ChatGPT

For monitoring, read reltuples from pg_class, which the planner keeps roughly current. It is off by a few percent between vacuums, which is fine for a dashboard and wrong for invoicing.

You

The index exists but EXPLAIN shows a sequential scan.

ChatGPT

Usually one of three things: the query returns a large fraction of the table so the scan really is cheaper, the types do not match so the index is not applicable, or statistics are stale. ANALYZE the table first, then compare with SET enable_seqscan = off to see what the planner thinks the index would cost.

You

Users see their own edits disappear after saving. Replica lag?

ChatGPT

Almost certainly. Route reads that follow a write by the same user to the primary for a short window, or track the write LSN in the session and wait for the replica to reach it. The general fix is read-your-writes consistency, not lower lag.