Slow Postgres, part 3 of 8. The SQL and raw numbers for every test are on GitHub.

Endpoint time per call
PostgreSQL 18, sampled every 5 seconds. Gaps: pgbench runs.

A retention job marked 463,418 of five million orders archived, a status ANALYZE had never seen, so Postgres estimated 1 row for it. An endpoint listing one customer's archived orders kept walking the status index, reading 463,418 entries to return one: 29 ms a call instead of 0.05 ms.

One note before the numbers: the AlphaVPS link at the end is a referral link, so I may get a commission at no extra cost to you, and the netcup voucher I offer there comes from my own account.

The short version:

  • A 1-row estimate for 463,418 archived orders kept a per-customer query on the wrong index: 29 ms a call against 0.05 ms after ANALYZE.
  • Autovacuum runs ANALYZE once 50 rows plus 10% of the table have changed, whatever the change. The 9.3% backfill sat under that line until 40,000 more rows changed. A manual ANALYZE took 190 ms.
  • PostgreSQL 18.7 and 17.12 picked the same plans with the same analyze threshold and similar timings. The only difference in behavior I measured is that 18 vacuums a frozen table much sooner after inserts, but still doesn't analyze it.
  • Run ANALYZE yourself after a job that loads or rewrites part of a table, and on temp tables after you fill them. Where a few percent can flip a plan, lower autovacuum_analyze_scale_factor for that table.
  • Correlated columns stay wrong with fresh statistics. CREATE STATISTICS fixes them after the next ANALYZE.

The lab: five million orders

PostgreSQL 18.7 in Docker on the 4-vCPU, 8 GB cloud VM from parts 1 and 2, with part 2's settings: 1 GB of shared_buffers, so the table stays in memory, and JIT and parallel workers off. Autovacuum runs with its defaults. The same scripts then ran on 17.12 in a fresh container. With everything in memory, 18's asynchronous I/O has nothing to speed up.

Five million orders, one every 11 seconds from January 2025 to September 2026. A million customers have five orders each, and each ships to one address: 20,000 postcodes in 21 cities, each city in one country. There are indexes on customer_id and status. The rows come from generate_series and setseed, so yours match mine on either version. Your pg_stats won't, because ANALYZE samples at random; my two runs differ a little too.

The endpoint lists one customer's orders in one status:

SELECT id, status, amount_cents, created_at FROM orders WHERE customer_id = 648065 AND status = 'archived'; 

Where row estimates come from

ANALYZE reads a random sample, 30,000 rows at the default default_statistics_target of 100, and stores a per-column summary, which you read in pg_stats. On this table it took 190 ms:

INFO: "orders": scanned 30000 of 53496 pages, containing 2803890 live rows and 0 dead rows; 30000 rows in sample, 4999897 estimated total rows 

18's ANALYZE VERBOSE adds buffer, WAL and CPU usage under that line; 17 stops there.

Estimates come from three parts of it. The first is the most common values (MCV) and their shares, here for status:

most_common_vals: {delivered,shipped,paid,cancelled,refunded} most_common_freqs: {0.8021333,0.07926667,0.059,0.039466668,0.020133333} 

status = 'paid' gets the table's 4,999,995 rows × 0.059 = 295,000. There are 300,322.

The second is n_distinct. A value that isn't in the common list gets an even share of the rows the list doesn't cover. customer_id has no common list, and its n_distinct is -0.202, meaning 20.2% of the rows: about 1,012,000 customers, so five rows each, which is exact.

The third is a histogram for ranges: 101 bounds that split the sampled values into 100 buckets with the same number of rows each. One week of June 2025 came out at 51,262 rows against 54,982.

default_statistics_target caps the common values and the buckets at 100 each and sets the sample at 300 times the target. At 1,000, ANALYZE read the whole table and took 1.6 seconds; at 10,000, 17 seconds, on both versions. Raise it per column (ALTER TABLE ... ALTER COLUMN ... SET STATISTICS) when the value you filter on doesn't make the top 100.

Back to status: its five frequencies add up to 1. As far as the planner knows, no rows are left for any other value, so it gets the minimum estimate, one row. That's right until somebody writes that status:

EXPLAIN SELECT * FROM orders WHERE status = 'archived'; Index Scan using orders_status_idx on orders (cost=0.43..8.45 rows=1 width=50) 

A backfill the statistics never saw

UPDATE orders SET status = 'archived' WHERE created_at < '2025-03-01'; -- UPDATE 463418, 3.9 s 

The endpoint's plan before the backfill, after it, and after ANALYZE (full plans in timeline-pg18.out):

before Index Scan using orders_status_idx rows=1 actual rows=0.00 Buffers: shared hit=3 0.019 ms after Index Scan using orders_status_idx rows=1 actual rows=1.00 Buffers: shared hit=5609 32.491 ms Rows Removed by Filter: 463417 ANALYZE Index Scan using orders_customer_id_idx rows=1 actual rows=1.00 Buffers: shared hit=10 0.027 ms 

That's 18's format: actual rows with two decimals, plus Buffers and an Index Searches line without asking. 17 prints rows=1 and needs BUFFERS spelled out, but it chose the same plans and read the same 5,609 pages.

The backfill didn't change the plan. With archived at 1 row, reading one status index entry and checking its customer costs 8.45 in planner units, against 24.52 for the five rows behind the customer_id index (part 1 covers how those units are priced). That was right while the status didn't exist. After the backfill every call fetched 463,418 archived entries and their rows to keep one.

Timed every five seconds for five minutes after the backfill, the plain query took a median of 29.0 ms over 52 samples, against 0.04 ms before it and 0.05 ms after ANALYZE (29.8 ms stale on 17). Four pgbench clients got 112 calls a second out of the stale endpoint and 180,353 after ANALYZE (118 and 188,180 on 17). A call that fast is hard to time, so the gap depends on the tool: 580 times by the psql medians, 1,600 times by pgbench throughput.

Why autovacuum left the table alone

Autovacuum analyzes a table once the rows inserted, updated or deleted since the last ANALYZE (n_mod_since_analyze in pg_stat_user_tables) pass

autovacuum_analyze_threshold + autovacuum_analyze_scale_factor × reltuples 50 + 0.1 × 4,999,897 = 500,040 

and it checks every autovacuum_naptime, one minute by default. PostgreSQL 18 kept this formula.

The backfill was 36,622 rows short. In the chart at the top, the counter sat at 463,418 for five minutes. Then I marked 40,000 shipped orders as delivered, the counter went to 503,418, and autovacuum analyzed the table about a second later. That second was luck, and so were the 60 seconds the 17 run waited at the same step: it depends on where the update lands in autovacuum's one-minute cycle. The ANALYZE took 0.55 s, and the estimate went to 455,197.

My five minutes ended because I wrote those rows. On a real table they end when 36,622 more rows change: at 1,000 a minute that's 37 minutes, at 100 a minute about six hours.

The docs say it plainly: autovacuum schedules ANALYZE "strictly as a function of the number of rows inserted or updated; it has no knowledge of whether that will lead to meaningful statistical changes." That catches slow drift. It misses:

  • a change under the line that lands on one value, like the backfill: 9.3% of the table and all of archived;
  • the wait for the next round, up to a minute, which a job that loads a batch and queries it right away always hits;
  • big tables, where the line moves too: at 100 million rows it's 10 million changed rows;
  • temporary tables, which autovacuum can't see, and partitioned tables, whose parent it never analyzes.

PostgreSQL 18 changed two autovacuum triggers, both for VACUUM. autovacuum_vacuum_max_threshold caps the dead-row trigger at 100 million rows, which bites only past 500 million. The insert trigger, 1,000 rows plus 20% of the table, now scales that 20% by the share of pages not yet frozen, and that is the one difference in behavior my lab measured between 17 and 18. With nothing frozen, both versions put the line at about 1,002,000 rows. After VACUUM (FREEZE) on a fresh copy, 18's line was 1,000 rows, and autovacuum vacuumed the table 19 seconds after a 400,000-row insert. 17's was 1,001,000, and nothing ran in three minutes. Neither analyzed the table, so October was still estimated at 540 rows against 400,000.

Two cheap fixes. Run ANALYZE at the end of the job that changed the table: 190 ms here, less than seven stale calls. And where a few percent can flip a plan, lower the line for that table:

ALTER TABLE orders SET (autovacuum_analyze_scale_factor = 0.01); 

That put the line at 54,090 rows. I moved 60,000 paid orders to a new status, on_hold, and autovacuum analyzed the table 43 seconds later. The estimate for on_hold went from 1 to 54,515. On a big table you can set a fixed count instead: autovacuum_analyze_scale_factor = 0 and autovacuum_analyze_threshold = 100000.

What the planner sees without ANALYZE

Stale statistics don't leave the planner blind. I loaded 400,000 orders for October and November 2026 in one INSERT, 8% of the table, and looked at estimates before any ANALYZE:

Estimated against actual rows before ANALYZE: new dates up to 746x off, a new status 1 against 463,418
EXPLAIN estimates on PostgreSQL 18 before ANALYZE, against counted rows. The archived row is from the backfill. 17's estimates were within 1% of these.

The row count was close: 5,358,467 against 5,400,000. pg_class still said 5,005,827 rows on 58,953 pages, but the planner reads the table's current size, 63,106 pages, and scales the old rows-per-page up to it.

The new dates were past the end of the histogram. Without an index on created_at, created_at >= '2026-10-01' got 536 rows against 400,000, and >= '2026-11-01' got 536 too: past the last bound, the planner won't go below a hundredth of one bucket. With an index, October got 44,291: the planner fetches the column's real maximum from the index and stretches the last bucket up to it. Nine times too low beats 746.

A temp table nobody analyzed has no statistics, so the planner guesses. I copied the 400,000 new orders into one. From its file size and a default row width the planner put it at 187,200 rows, then took 0.5% of that for an equality: status = 'shipped' came out at 936 rows against 120,138. After ANALYZE: 120,533.

Correlated columns: fresh statistics, wrong estimate

ANALYZE fixes statistics that are old. It can't fix part 2's problem, two correlated columns multiplied into 300 rows instead of 15,000 on PostgreSQL 17, because the planner keeps statistics per column. For country = 'PT' AND city = 'Lisbon' it multiplies the two shares as if they were independent, 1.99% × 1.54%, and gets 1,650 rows. Of the 5.4 million rows, 81,000 match: every Lisbon order ships to PT.

CREATE STATISTICS keeps statistics on a group of columns. Each of its three kinds fixes a different estimate:

Estimates with no extended statistics, dependencies, mcv and ndistinct against the real counts
Estimates from EXPLAIN on PostgreSQL 18 after ANALYZE, on a log scale. 17 came within 10% of each.

dependencies records how far one column decides another: city decides country completely (1.0), country decides city 18% of the way. The Lisbon estimate went to 75,574. It assumes the values in your query agree, though: country = 'ES' AND city = 'Lisbon' matches nothing and also got 75,574, worse than 9,955 without extended statistics. It only works for = and IN.

mcv stores the most common combinations, here all 21 pairs, and works for ranges too. It gave 79,919 for PT and Lisbon and 1 for ES and Lisbon.

ndistinct counts distinct combinations, which GROUP BY needs. GROUP BY city, postcode was estimated at 21 × 20,164 = 423,444 groups. There are 20,000, since every postcode sits in one city. With ndistinct: 20,156.

Two catches. Nothing changes until the next ANALYZE: right after CREATE STATISTICS the Lisbon estimate was still 1,650. And they go stale with the table. Leave out the kind and you get all three:

CREATE STATISTICS orders_country_city ON country, city FROM orders; ANALYZE orders; 

With that and a second object on (city, postcode), the three estimates were 83,942, 1 and 20,123, and ANALYZE went from 175 ms to 352 ms. The planner uses them for conditions on one table, like part 2's users scan, not for joins.

pg_upgrade to 18 now carries most planner statistics over, but not the ones from CREATE STATISTICS. The upgrade docs have you run vacuumdb --all --analyze-in-stages --missing-stats-only for the gaps, then vacuumdb --all --analyze-only.

How to check this on your own database

  1. In EXPLAIN ANALYZE, find the lowest node where estimated and actual rows differ by 10x or more.
  2. See how much its table changed since the last ANALYZE, with the query below.
  3. Look the value up in pg_stats: is it in most_common_vals, and is a range past the last histogram bound?
  4. Run ANALYZE on the table and EXPLAIN again. If that fixed it, apply one of the two fixes above.
  5. If it's still wrong and the filter uses columns that depend on each other, create statistics on them and ANALYZE.
SELECT relname, n_live_tup, n_mod_since_analyze, last_analyze, last_autoanalyze FROM pg_stat_user_tables ORDER BY n_mod_since_analyze DESC; 

Run it on your own server

Everything here ran on one 4-vCPU AMD EPYC cloud VM with 8 GB of RAM: PostgreSQL 18.7 first, then 17.12, each in a fresh Docker container. Your milliseconds will differ. The SQL, the raw output of both versions and the chart code are on GitHub, and sh bench/run.sh 18 (or 17) reruns the whole lab in about 20 minutes. Run it on your own server, and if you get a different picture or think I got something wrong, open an issue or a PR.

My own projects run on netcup (VPS from €2.21 a month) and AlphaVPS (VPS from €2.54 a month). For netcup, message me on LinkedIn and I'll send you a €5 voucher for new customers.

Good luck with your plans. Part 4 is next: column order in a composite index, and what PostgreSQL 18's skip scan changes there.

Finish

I hope you understood the instructions correctly. If you have any edits to this article, I will be waiting for your comments. If I really helped you, I kindly ask you to subscribe to my LinkedIn and provide feedback on this article.

Link to follow me:

LinkedIn

All my articles and links: fomo.moe