Quick revision
The short answer
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'.
What to remember
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'.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
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.
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.
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.
| Option | Speed | Exact? | Good for |
|---|---|---|---|
SELECT count(*) | minutes on 500M rows | yes | rare jobs, audits |
| Index-only scan count | faster if well vacuumed | yes | medium tables |
pg_class.reltuples | instant | no, refreshed by vacuum and analyze | dashboards, totals |
| EXPLAIN row estimate | instant | no | approximate search results |
| Counter table | instant | yes, if maintained | counts shown constantly |
| Capped count (10,001) | fast | exact 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.
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'.
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.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
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/