Why is COUNT(*) slow in Postgres? We measured it on 10 million rows
Why SELECT count(*) in PostgreSQL reads the whole table, and what to do instead. Measured on 10 million rows on Postgres 17.11: sequential vs parallel vs index-only scans, how an UPDATE of 1% of rows made an indexed count 40 to 50 times slower until VACUUM ran, count(*) vs count(1), planner estimates, capped counts, and the write cost of trigger-maintained counter tables.
On this page
Your list page shows "1,284,551 orders", and the query behind that number is now the slowest one on the page. SELECT count(*) in PostgreSQL has no stored row count to return: because of MVCC, how many rows a table has depends on who is asking, so Postgres has to look at the rows. This post loads 10 million orders into PostgreSQL 17.11 (Relyt One runs PostgreSQL 17) and measures what a count actually costs: a full count with and without parallel workers, an index-only scan, a filtered count before and after an UPDATE, the planner's estimates, capped counts, and counter tables kept by triggers. Every number comes from a script you can rerun, and the first section maps what you need to the cheapest way to get it.
Decide what the number is for, then pick the method:
- An exact total of a big table, on every page view: you can't make it cheap. Cache it, estimate it, or keep a counter table, and accept the write cost.
- An exact count with a selective filter (
WHERE status = 'pending'): an index on the filter column, and a table that VACUUM keeps up with, so Postgres can use an index-only scan. - "About how many?":
pg_class.reltuplesfor a whole table, the planner's estimate for a filtered query. Both cost almost nothing and both can be wrong. - "More than 1,000?" or "Any at all?": count up to a limit, or use
EXISTS. Both stop early.
PostgreSQL keeps old and new versions of a row side by side, and each statement sees the row versions that were committed when its snapshot was taken, plus its own transaction's uncommitted changes. Two sessions can look at the same table at the same moment and both be right about different counts:
CREATE TABLE visits (id int);
INSERT INTO visits SELECT generate_series(1, 10);
-- session A
BEGIN;
INSERT INTO visits SELECT generate_series(11, 13);
SELECT count(*) FROM visits; -- 13
-- session B, while A is still open
SELECT count(*) FROM visits; -- 10
-- session A
COMMIT; -- now both sessions see 13A single counter in the table header can't serve both sessions. So count(*) does what any other query does: it reads row versions and checks, one by one, whether each is visible to the current snapshot. The cost is proportional to the number of rows, and on a big table that is a lot of rows.
One table of 10 million orders. A quarter of the rows are spread over four non-delivered statuses (2% pending), and 30% of the rows carry a 64-character note:
SELECT setseed(0.42);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id int NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
total numeric(10,2) NOT NULL,
note text
) WITH (autovacuum_enabled = off); -- so we can look at the table before any VACUUM
INSERT INTO orders (customer_id, status, created_at, total, note)
SELECT 1 + (random() * 99999)::int,
CASE WHEN r < 0.02 THEN 'pending'
WHEN r < 0.10 THEN 'paid'
WHEN r < 0.20 THEN 'shipped'
WHEN r < 0.95 THEN 'delivered'
ELSE 'cancelled' END,
timestamptz '2025-01-01' + (g * interval '3 seconds'),
round((5 + random() * 495)::numeric, 2),
CASE WHEN random() < 0.3 THEN md5(g::text) || md5((g + 1)::text) END
FROM (SELECT g, random() AS r FROM generate_series(1, 10000000) g) s;The table is 838 MB on disk (107,303 pages of 8 kB) and the primary key index is 214 MB. Autovacuum is switched off for this table only so we control when VACUUM runs; in production, leave it on.
How we measured: Docker postgres:17.11-alpine with the default configuration (128 MB shared_buffers, up to 2 parallel workers per query), on an Apple M1 Pro with 5 CPUs given to Docker. Each timing is the median of 9 runs after one warm-up run, measured inside the server, so the data is in the operating system's cache and there is no network in the numbers. We ran the full script three times, each time in a fresh container. The second run shared the machine with other work and was slower on several queries, so the ranges in the text come from the first and third runs. Your hardware will give different absolute numbers; the ratios are the point.
Right after the INSERT, before any VACUUM, we ran EXPLAIN (ANALYZE, BUFFERS) on the count twice:
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) SELECT count(*) FROM orders;Parallel Seq Scan on orders (actual rows=3333333 loops=3)
Buffers: shared hit=12869 read=94434 dirtied=94672 written=94432
Execution Time: 655.847 msThat run took 656 ms; in the other clean run the first count took 1,076 ms. The second run of the same query took 223–234 ms and dirtied nothing. The difference is hint bits. The first time a row version is examined, Postgres records in the row itself that the transaction that wrote it has committed, so later readers don't have to look that up again. That is a write, and a plain count(*) right after a load triggers it for every row: here about 94,700 of the 107,303 pages were dirtied and written back by a query that only reads. (The rest were still dirty from the INSERT itself.) The PostgreSQL wiki describes this as "heavy writes to a database table even though you're just reading from it".
The fix is to run VACUUM (or VACUUM ANALYZE) yourself after a large load, so that cost is paid once, by a maintenance command, and not by the first user who opens the dashboard.
After VACUUM and ANALYZE, counting the whole table:
- Parallel sequential scan (the plan Postgres picked): 136–153 ms
- Sequential scan, no parallel workers: 321–326 ms
- Index-only scan on the primary key, parallel (forced with
enable_seqscan = off): 299–304 ms - Index-only scan, no parallel workers: 438–483 ms
Two things to take away. First, the planner's default was the fastest: two parallel workers plus the leader split the table three ways, and the time dropped by more than half. If you've turned max_parallel_workers_per_gather down to 0, counts are one of the places you pay for it.
Second, an index didn't make the full count faster. The index-only scan read 4 times fewer pages (27,337 instead of 107,303) and reported Heap Fetches: 0, yet it was slower, probably because it still produces 10 million index entries one by one, and with the data cached, per-row work matters more than page reads. The advice "add an index to speed up count(*)" doesn't hold for an unfiltered count of a cached table. Where fewer pages matter more, on a table much bigger than memory, an index-only scan can win; check with EXPLAIN (ANALYZE, BUFFERS) on your own data.
Either way, a full count grows with the table. Expect ten times the rows to take at least ten times as long, and more once the table no longer fits in memory.
Same table, no parallel workers, median of 9:
- count(*): 324–367 ms
- count(1): 351–367 ms
- count(id): 412–420 ms
- count(note): 581–588 ms
count(*) and count(1) were within noise of each other in our runs; neither is a trick for the other. count(column) is slower and means something else. The documentation defines count(*) as "the number of input rows" and count(expression) as "the number of input rows in which the input value is not null". On our table count(*) returned 10,000,000 and count(note) returned 3,001,185. Use count(*) unless you mean to skip NULLs.
Most counts in an application have a filter. With an index on the filter column, Postgres can count matching index entries and skip the table, but only for pages it knows are fully visible. That knowledge lives in the visibility map, which keeps an all-visible bit for every table page (plus an all-frozen bit) meaning "every row on this page is visible to all transactions". VACUUM sets the bits; any INSERT, UPDATE or DELETE on a page clears its bit.
CREATE INDEX orders_status ON orders (status);
VACUUM ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF)
SELECT count(*) FROM orders WHERE status = 'pending';Index Only Scan using orders_status on orders (actual rows=200440 loops=1)
Index Cond: (status = 'pending'::text)
Heap Fetches: 0
Buffers: shared hit=4 read=171175 pages read, 6.5–6.8 ms. With index-only scans disabled, the same count used a parallel bitmap heap scan and took 253–261 ms.
Then we updated 1% of the rows, one in every hundred, changing a column that isn't indexed:
UPDATE orders SET total = total + 1 WHERE id % 100 = 0;With about 93 rows on each page, one in a hundred touches nearly every page. The pg_visibility extension shows what that did to the map:
CREATE EXTENSION pg_visibility;
SELECT count(*) FILTER (WHERE all_visible) AS all_visible, count(*) AS pages
FROM pg_visibility_map('orders');Before the update: 107,303 of 107,303 pages all-visible. After: 7,546 of 108,374, about 7%. The same count now looked like this:
Index Only Scan using orders_status on orders (actual rows=200440 loops=1)
Index Cond: (status = 'pending'::text)
Heap Fetches: 188584
Buffers: shared hit=3 read=85759 dirtied=85584 written=83906
Execution Time: 3550.609 msIt's still called an index-only scan, but it visited the table for 188,584 of the 200,440 rows. The first run also paid the hint-bit writes from the previous section and took 3.6–5.1 seconds; after that the median was 270–330 ms, 40 to 50 times slower than before the update. VACUUM orders set all 108,374 bits again, and the count went back to 6.5–6.6 ms.
The documentation is blunt about this: an index-only scan "will be a win only if a significant fraction of the table's heap pages have their all-visible map bits set". So for fast filtered counts, the thing to tune is how soon VACUUM runs after writes.
By default, autovacuum vacuums a table once its dead rows exceed autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor × rows, which is 50 + 0.2 × rows. On our 10 million row table that is about 2 million dead rows. Our 100,000 updates were 5% of that, so autovacuum would have left 93% of the visibility map cleared until roughly another 1.9 million rows were updated or deleted. Insert-only tables have a separate threshold with the same 20% default (autovacuum_vacuum_insert_scale_factor).
For a large table whose counts matter, lower the scale factors for that table only:
ALTER TABLE orders SET (
autovacuum_vacuum_scale_factor = 0.01,
autovacuum_vacuum_insert_scale_factor = 0.01
);Two things defeat this no matter how you tune it. A long-running or idle-in-transaction session keeps old row versions alive, so VACUUM can't mark their pages all-visible. And a table that is updated everywhere all the time will never stay all-visible for long; for those, use one of the approaches below.
A pager that says "about 1.2M results" doesn't need an exact count. Postgres keeps two cheap numbers per table:
SELECT reltuples::bigint FROM pg_class WHERE relname = 'orders';
SELECT n_live_tup FROM pg_stat_user_tables WHERE relname = 'orders';reltuples is the planner's estimate, updated by VACUUM, ANALYZE and some DDL such as CREATE INDEX. It is -1 for a table that has never been vacuumed or analyzed, which is what we saw right after the load. n_live_tup comes from the statistics system and is documented as an "estimated number of live rows". After ANALYZE both returned 10,000,081 in one run and 9,999,474 in the other, for a table with exactly 10,000,000 rows.
For a filtered count, ask the planner. This function, adapted from the PostgreSQL wiki, runs EXPLAIN and returns its row estimate without executing the query:
CREATE FUNCTION count_estimate(query text) RETURNS bigint
LANGUAGE plpgsql AS $$
DECLARE plan jsonb;
BEGIN
EXECUTE 'EXPLAIN (FORMAT JSON) ' || query INTO plan;
RETURN (plan -> 0 -> 'Plan' ->> 'Plan Rows')::bigint;
END $$;
SELECT count_estimate($$SELECT 1 FROM orders WHERE status = 'pending'$$);It concatenates SQL, so never pass it user input; build the query string yourself. How good were the estimates?
- status = 'pending': estimated 204,335 and 210,322, actual 200,440
- customer_id = 4242: estimated 101 and 100, actual 96
- note LIKE '%abc%': estimated 297 and 60,461, actual 45,006
Equality on a column with statistics is close. A pattern match in the middle of a string is something the planner can't model well: it was off by a factor of 150 in one run and by a third in the other, depending on which rows ANALYZE happened to sample.
Estimates are also only as fresh as the last ANALYZE. We simulated a flash sale, 1 million new pending orders, and asked again before any ANALYZE (autovacuum is off on this test table; in production this is the window before autovacuum's ANALYZE gets to it):
- reltuples: unchanged
- n_live_tup: up by exactly 1,000,000
- Planner, whole table: 10,673,864 for an actual 11,000,000
- Planner, pending: 218,103 for an actual 1,200,440
The whole-table estimate moved even without ANALYZE, because the planner scales reltuples by the table's current size in pages. The filtered one was off by a factor of 5.5 (5.3 in the other run), because the share of pending rows came from statistics gathered before the sale. After ANALYZE it was 1,232,043 (1,187,081 in the other run). If you show estimates, label them as estimates, and make sure autovacuum's ANALYZE keeps up with the tables you estimate.
Many interfaces only need a threshold: "1,000+ orders", or whether to show an empty state. Both can stop early:
-- "1,000+": stops after 1,001 matching rows
SELECT count(*) FROM (
SELECT 1 FROM orders WHERE status = 'delivered' LIMIT 1001
) s;
-- "is there anything?": stops at the first match
SELECT EXISTS (SELECT 1 FROM orders WHERE status = 'cancelled');The exact count of the 7.5 million delivered orders took 93–95 ms. The capped count took 0.07 ms and EXISTS 0.03 ms. If the capped count returns 1,001, show "1,000+". For pagination, you don't need a total at all to know whether there's a next page; keyset pagination asks for one row more than the page size instead.
If you really need an exact total of a big table on every request, maintain it. A trigger that adds and subtracts from a counter row makes the read a single-row lookup:
CREATE TABLE row_count (tbl regclass PRIMARY KEY, n bigint NOT NULL);
INSERT INTO row_count VALUES ('items_one', 0);
CREATE FUNCTION bump_row_count() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
UPDATE row_count
SET n = n + CASE TG_OP WHEN 'INSERT' THEN 1 ELSE -1 END
WHERE tbl = TG_RELID::regclass;
RETURN NULL;
END $$;
CREATE TRIGGER items_one_count AFTER INSERT OR DELETE ON items_one
FOR EACH ROW EXECUTE FUNCTION bump_row_count();The catch is that every writer now updates the same row, and a row can be updated by only one open transaction at a time. Under concurrency, inserts queue behind each other's counter update until each transaction commits. We measured it with pgbench, 16 clients each inserting single rows for 15 seconds, two rounds per run, on three otherwise identical tables:
- No counter: 34,890–47,801 inserts/s
- One counter row: 5,395–7,226 inserts/s
- 16 counter rows: 23,978–27,448 inserts/s
A single counter row cut insert throughput by about 6 times. Spreading the counter over 16 rows, each write picking one at random and reads summing them, ran at 53–73% of the no-counter rate, roughly 4 times the single-row rate:
CREATE TABLE row_count_shard (
tbl regclass,
shard int,
n bigint NOT NULL DEFAULT 0,
PRIMARY KEY (tbl, shard)
);
INSERT INTO row_count_shard (tbl, shard)
SELECT 'items_sharded', s FROM generate_series(0, 15) s;
CREATE FUNCTION bump_row_count_shard() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE s int := floor(random() * 16); -- pick once; random() inside WHERE runs per row
BEGIN
UPDATE row_count_shard
SET n = n + CASE TG_OP WHEN 'INSERT' THEN 1 ELSE -1 END
WHERE tbl = TG_RELID::regclass
AND shard = s;
RETURN NULL;
END $$;
CREATE TRIGGER items_sharded_count AFTER INSERT OR DELETE ON items_sharded
FOR EACH ROW EXECUTE FUNCTION bump_row_count_shard();
SELECT sum(n) FROM row_count_shard WHERE tbl = 'items_sharded'::regclass;Note the variable. Our first version wrote AND shard = floor(random() * 16)::int directly in the WHERE clause. random() is volatile, so Postgres evaluated it again for every candidate row, and again whenever it rechecked a row that another transaction had just updated. An insert could update zero, one or several shards. With one client the errors roughly cancelled out (50,789 counted for 51,247 rows in a 10-second run), but with 16 concurrent writers most of those rechecks failed, and the counter said 73,357 for a table with 126,846 rows. Picking the shard once fixed it: at the end of the final run, both counters matched count(*) exactly.
Three more things to handle before trusting a counter table:
TRUNCATEdoesn't fireON DELETEtriggers. Add a statement-levelAFTER TRUNCATEtrigger that resets the counter, or don't truncate counted tables.- The counter rows are updated constantly and need VACUUM like any other hot table.
- The trigger runs inside the writing transaction, so the counter is exactly as consistent as the data. That's the point, and also the cost.
- Ask what the number is for. Most "how many" questions are "about how many" or "more than N".
- Run
VACUUM ANALYZEafter bulk loads, before anyone queries the table. - For exact filtered counts, index the filter column and check for
Heap Fetches: 0inEXPLAIN (ANALYZE). - If
Heap Fetchesis high, lowerautovacuum_vacuum_scale_factoron that table and look for long-running transactions. - For totals in the UI, use
reltuplesorcount_estimate, and label them as approximate. - For "1,000+" or empty states, use a capped count or
EXISTS. - Keep a counter table only when you need exact totals often, and shard it if many sessions write at once.
For index problems that aren't about counting, see why Postgres is not using your index.
Everything here is plain PostgreSQL 17; pg_visibility is a contrib extension we used only to look at the map. The numbers that decide your design come from your own tables, though: how many pages your updates touch, how far behind autovacuum runs, how close the planner's estimates are. On Relyt One, a branch is a cheap place to find out. It starts from the parent's data with copy-on-write storage and runs on its own compute, so you can run full counts, try per-table autovacuum settings and benchmark a counter trigger, then delete the branch, without adding load to production.
The PostgreSQL manual covers the background in Index-Only Scans, Updating the Visibility Map and The Autovacuum Daemon.



