System design Level 3 This level · 21 of 45
Medium postgresql sql

Why is COUNT(*) slow on a large table, and what do you do about it?

The 30 second answer

Because of MVCC, different transactions can see different rows, so PostgreSQL has no stored row count and must check row visibility, scanning the table or an index. For exact counts on a filtered set, a matching index allows an index-only scan if the visibility map is current. For UI totals, use the planner's estimate from pg_class or EXPLAIN, show "more than N", or fetch one extra row to know if there's a next page.

Could you say this in an interview?

From the basics. PostgreSQL keeps several versions of a row so readers and writers don't block each other (MVCC). The wiki explains that because "multiple transactions can see different states of the data", there's "no straightforward way for COUNT(*)" to read a single stored number; it has to look at rows and check which are visible.

Options.

  1. Don't count. A listing page needs "is there a next page?", not "page 1 of 41,327". Fetch LIMIT 21 for a 20-row page.
  2. Estimate. The wiki: "If you don't need an exact count, the current statistic from the catalog table pg_class might be good enough":
   SELECT reltuples::bigint AS estimate FROM pg_class WHERE oid = 'public.orders'::regclass;

For a filtered count, the row estimate in EXPLAIN (without ANALYZE) is another approximation.

  1. Count with an index. An index on the filter columns can give an index-only scan, which skips the heap for pages marked all-visible.
  2. Maintain a counter. A summary table updated by the application or a trigger, or a materialized view refreshed on a schedule. That trades write cost and staleness for instant reads.

Badly written.

SELECT count(*) FROM orders WHERE status = 'DONE';   -- on every page view
SELECT * FROM orders WHERE status = 'DONE' ORDER BY created_at DESC LIMIT 20 OFFSET 0;

Better.

SELECT id, created_at FROM orders WHERE status = 'DONE'
ORDER BY created_at DESC LIMIT 21;     -- 21st row means "show Next"

Trade-offs.

  • Estimates can be off after bulk changes until ANALYZE runs.
  • Trigger-maintained counters create a hot row that every insert updates; spread it across several rows or batch updates.
  • The same choice exists in Elasticsearch: track_total_hits defaults to counting exactly up to 10,000, and exact counts cost more.

Alternate interview scenarios

"The admin dashboard shows total orders per status and it's slow."

Use a materialized view or summary table refreshed every few minutes, and say how stale the number may be.

"Product wants 'Showing 1 to 20 of 1,234,567'."

Offer an approximate total ("over 1 million") from statistics, or an exact count computed asynchronously and cached.

"You must prove a 30-minute bulk load of about 2 billion rows lost nothing. How do you count?"

An exact count is the only proof, but at that size it is an audit job, not a dashboard query. In a public load test, the exact count on a views table of about 1.8 billion rows ran alongside a line count of a 175 GB log, and the two took about another 10 minutes, with the database reading close to half a gigabyte per second from disk. An approximate count returned about 1.1 billion right after the load, while the true number was 1.8 billion. So for a user-facing number I use the estimate and say how stale it can be; reltuples in pg_class is only refreshed by VACUUM, ANALYZE and a few DDL commands, so I run ANALYZE after a big load. For verification I compare per-batch counts recorded by the loader with request counts per interval, and keep the full exact count for an offline check.

Sources (4)
  1. PostgreSQL wiki: Slow countingwiki.postgresql.org
  2. PostgreSQL wiki: Count estimatewiki.postgresql.org
  3. PostgreSQL docs: Index-only scans and covering indexespostgresql.org
  4. PostgreSQL docs: pg_class (reltuples)postgresql.org
Previous
Next