Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Why is SELECT COUNT(*) FROM orders slow on a 500 million row PostgreSQL table, and what faster options exist?

PostgreSQL keeps no stored row count, because with MVCC each transaction may see a different set of rows, so COUNT(*) must actually visit rows to check which ones are visible to us. It can use an index-only scan of a small index when the visibility map marks most pages all-visible; otherwise it reads the whole heap. Faster options are an estimate from pg_class.reltuples or EXPLAIN, a counter table maintained by triggers or the application for exact counts needed often, and asking whether the UI really needs more than 'over 10,000'.

Why this question is asked

COUNT(*) looks like the simplest query there is, and on a 500 million row table it can take minutes. Developers coming from databases or engines that answer it instantly are often surprised, and the reason teaches something central about how PostgreSQL handles concurrency. Interviewers ask it because the answer shows whether we understand MVCC and whether we think about what the product actually needs. In this answer, we will recap MVCC, see why it rules out a stored count, look at how PostgreSQL counts, and then go through the faster options.

1A Quick Recap of MVCC

MVCC, multi-version concurrency control, is how PostgreSQL lets readers and writers work at the same time without blocking each other. When a row is updated, PostgreSQL does not overwrite it; it writes a new version and marks the old one as replaced. When a row is deleted, the old version stays until vacuum removes it. Each row version records which transaction created it and which one ended it.

Each query reads with a snapshot, a record of which transactions had committed when it started. A row version is visible to us only if it was created by a transaction in our snapshot and not yet removed by one. So two sessions running COUNT(*) at the same moment can correctly get different answers, if one of them started before a big insert committed.

2Why There Is No Stored Count

Because visibility depends on the snapshot, there is no single number of rows that is right for everyone. A stored counter would have to be right for every possible snapshot at once, which is impossible, or be updated by every insert and delete, which would turn one counter row into a hot spot that every write must lock. PostgreSQL chooses neither, so COUNT(*) has to look at the rows and check each one's visibility.

Java
SELECT count(*) FROM orders;
-- Finalize Aggregate
-- -> Gather (Workers Planned: 4)
-- -> Partial Aggregate
-- -> Parallel Seq Scan on orders -- reads every page of a 500 million row table
-- Execution Time: about 95 s on this example (illustrative)

Notice that PostgreSQL already does its best: it splits the scan across parallel workers. But the work is still proportional to the size of the table, and for 500 million rows that means reading tens or hundreds of gigabytes.

3When an Index-Only Scan Helps

A smaller structure can sometimes stand in for the table. An index on a narrow column is much smaller than the table, and PostgreSQL can count its entries with an index-only scan. There is a catch: index entries do not store visibility information, so the database must still check whether each row is visible. It avoids visiting the table only for pages that the visibility map marks as all-visible, meaning every row on the page is visible to every transaction. Vacuum sets those marks.

Java
SELECT count(*) FROM orders;
-- Aggregate -> Index Only Scan using orders_pkey on orders
-- Heap Fetches: 1200 -- few heap visits: the visibility map is mostly set
-- On a table with heavy recent updates the same plan shows
-- Heap Fetches: 140000000 -- most pages not all-visible, nearly as slow as a seq scan

So a well-vacuumed table with a small index counts noticeably faster, while a table with many recent changes gains little. This is an improvement, not a solution: the work still grows with the number of rows.

4Faster Option 1: Use an Estimate

Often we do not need the exact number. PostgreSQL keeps an estimate of each table's row count in pg_class.reltuples, refreshed by VACUUM and ANALYZE, and the planner's estimate for any query is available from EXPLAIN.

SQL
SELECT reltuples::bigint AS estimate FROM pg_class WHERE oid = 'public.orders'::regclass;
-- 501234880 (instant; -1 means never analyzed, in PostgreSQL 14 and later)
EXPLAIN SELECT * FROM orders WHERE status = 'PENDING';
-- Seq Scan on orders (cost=... rows=48210 ...) -- the planner's estimate for a filtered count
Ways to answer 'how many orders?'
OptionSpeedExact?Good for
SELECT count(*)minutes on 500M rowsyesrare jobs, audits
Index-only scan countfaster if well vacuumedyesmedium tables
pg_class.reltuplesinstantno, refreshed by vacuum and analyzedashboards, totals
EXPLAIN row estimateinstantnoapproximate search results
Counter tableinstantyes, if maintainedcounts shown constantly
Capped count (10,001)fastexact up to the cap'more than 10,000' in a UI

Notice that the EXPLAIN trick works for filtered counts too, which some search screens use to show an approximate number of results. Estimates can be off by a few percent, or more just after a bulk load, so they suit dashboards and result counts, not invoices.

5Faster Option 2: Maintain a Counter

When an exact count is shown constantly, we can maintain it as data. A trigger, or the application in the same transaction, updates a counter row on each insert and delete, and reading becomes a single-row lookup.

SQL
CREATE TABLE order_counts (id int PRIMARY KEY, n bigint NOT NULL);
CREATE FUNCTION bump_order_count() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
UPDATE order_counts SET n = n + CASE WHEN TG_OP = 'INSERT' THEN 1 ELSE -1 END WHERE id = 1;
RETURN NULL;
END $$;
CREATE TRIGGER orders_count AFTER INSERT OR DELETE ON orders
FOR EACH ROW EXECUTE FUNCTION bump_order_count();
SELECT n FROM order_counts WHERE id = 1; -- instant

The catch is write contention. Every insert now updates the same row, and two concurrent transactions updating it must wait for each other, so a busy table can become slower to write. Splitting the counter across several rows and summing them, or applying increments asynchronously, reduces that, at the cost of complexity.

6Faster Option 3: Ask What the Screen Needs

The cheapest count is the one we do not run. A user looking at a list rarely cares whether there are 1,204,377 or 1,204,378 results; 'more than 10,000' or 'about 1.2 million' is enough, and pagination can show 'next' without a total. A capped count, SELECT count(*) FROM (SELECT 1 FROM orders WHERE status = 'PENDING' LIMIT 10001) t, stops after 10,001 rows and lets the UI show '10,000+'. Exact totals are worth their price where they carry meaning, such as billing or compliance reports.

7Follow-up questions

Why does MySQL InnoDB have the same problem?

InnoDB also uses MVCC, so it cannot keep one stored count either and must scan an index to count. The old MyISAM engine kept an exact row count because it had no transactions, which is why the expectation of an instant COUNT(*) exists.

Is COUNT(1) faster than COUNT(*)?

No. In PostgreSQL COUNT(*) is in fact slightly simpler, because COUNT(1) evaluates an expression per row. Both must visit the same rows, so the choice changes nothing meaningful.

How accurate is reltuples?

It is updated by VACUUM, autovacuum and ANALYZE, so it is usually within a few percent on a regularly maintained table. Right after a large load or delete it can be far off until the next analyze, which is why it suits displays rather than decisions.

8Conclusion

In this answer, we saw that PostgreSQL cannot keep a stored row count because MVCC gives each transaction its own view of which rows exist, so COUNT(*) must visit rows and check visibility. An index-only scan helps only when the visibility map is mostly set. For speed we use estimates from reltuples or EXPLAIN, a maintained counter when an exact count is needed often, accepting write contention, or a capped count when the UI only needs 'more than 10,000'.

What to say in the interviewAbout 90 seconds aloud

Open with

PostgreSQL uses MVCC, so updates and deletes leave old row versions, and each transaction sees the rows that are visible in its own snapshot. That means there is no single correct row count to store: two transactions can legitimately see different numbers.

Then, if they want more

So COUNT(*) has to visit the rows and check visibility for each one, which on 500 million rows is a full, if parallel, scan. It can use an index-only scan on a small index, but that only avoids the heap for pages the visibility map marks all-visible, so on a table with lots of recent updates it gains little.

If an estimate is enough, I read reltuples from pg_class, which vacuum and analyze keep up to date, or the planner's row estimate from EXPLAIN for a filtered query.

If the product really needs an exact count often, I maintain a counter table, updated by a trigger or by the application in the same transaction, accepting that every write now touches one hot row, which I can spread across several rows. And I would ask the product question: does the screen need an exact number?

Usually 'more than 10,000' is fine, which I can get with a count over a subquery limited to 10,001 rows, or I can drop the total and just offer a next page.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 14
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why is SELECT COUNT(*) FROM orders slow on a 500 million row PostgreSQL table, and what...": https://scrivio-interview-library.netlify.app/databases/query-optimization/a118ceae3d/