Query planning and performance: EXPLAIN, statistics, slow queries, tuning

How a database decides how to run your SQL, why it sometimes decides badly, and the routine that finds and fixes slow queries, measured on a real PostgreSQL with the chat product's 10 million messages. A child page of Topic: databases; sources are linked inline; data as of October 2026. Reading: 45 min, plus 11 in closed details.

The idea in one screen

The planner never runs the alternatives: it predicts how many rows each step will produce from a sampled summary of your data, prices each candidate plan from those row estimates, and runs the cheapest. So a slow query is almost always a wrong estimate, a missing access path, or an application asking the wrong way, and the diagnosis starts by putting the estimated rows next to the actual rows.

Fig. 1 follows one slow search from the chat product (section 7), a real plan on PostgreSQL 16.2: SELECT id, title FROM chats WHERE title LIKE 'Chat 123456%' ORDER BY id LIMIT 10. Titles are 'Chat ' plus the chat's id, so exactly one chat matches, and it sits about an eighth of the way through the table.

  1. Statistics. ANALYZE keeps a summary of a sample of 30,000 rows (most common values, a histogram). From it the planner estimates that 100 titles match 'Chat 123456%'.
  2. Cost: the Limit makes walking the key look cheap. With 100 matches spread through the table, walking the primary key in id order should find the first 10 after about a tenth of it: cost 3,780 for the Limit, out of 37,801 for the whole walk. Sorting every match looked dearer, so this plan won.
  3. Execution: 1 title matched. The walk found chat 123,456 early, then never collected 10 rows, so it read all 1,000,000 chats through the index: 999,999 rows removed by the filter, 12,053 pages (all found in memory), 91.6 ms.
  4. EXPLAIN ANALYZE shows where it broke. At the scan node, estimated rows=100 against actual rows=1: compare 100 with 1. The lowest node where the two disagree is where the plan went wrong; every section below elaborates one part of this path: statistics (3, 4), costs (2), joins (5), reading the plan (6), the routine and the fixes (7, 8).
  5. The fix: an index on the column you filter. CREATE INDEX ON chats (title) turns the prefix into a range: one descent of the new B-tree straight to the match, 7 pages and 0.078 ms instead of 12,053 pages and 91.6 ms.

You need: SQL joins and GROUP BY (SQL and data modelling) and what a B-tree index is (Storage engines and indexes). Running example: the chat product of Topic: databases, 100,000 users, 1,000,000 chats and 10,000,000 messages in one PostgreSQL ("Postgres") database of about 4 GB, plus a billing table in section 10. measured: on PostgreSQL 16.2, Apple M1 Pro laptop (10 cores, 16 GB), best of three on a shared machine, so trust page counts over milliseconds; illustrative: an input made up to show a shape.

Planner (optimizer)
the part of the database that turns SQL into a plan by estimated cost.
Cardinality, selectivity
rows a node outputs; the fraction of rows a condition keeps (estimated rows = selectivity × rows).
Cost
the planner's price in arbitrary units, one sequential page read = 1.0; startup cost before the first row, total after the last.
Statistics
what ANALYZE stores per column from a sample: null fraction, distinct count, most common values (MCV list), histogram, correlation.
Correlation
how closely a table's physical row order follows a column's order, from -1 to 1.
Extended statistics
statistics over several columns, made with CREATE STATISTICS.
Custom and generic plan
for a prepared statement, a plan for the actual parameter values, or one plan reused for all.
Spill
a sort or hash that outgrows work_mem and writes temporary files.
Every section in one table, with what was measured (reference)
SectionThe ideaMeasured here
1A query goes through parse, rewrite, plan, execute. The plan is a tree of steps.
2The planner prices every candidate plan in made-up units: pages read plus rows processed, each with a weight.This page's formulas reproduce 150 of 150 planner cost figures to the cent
3Prices depend on row counts, which come from statistics that ANALYZE computes from a sample.Distinct users in chats: estimated 75,971, really 99,945
4Estimates break on correlated columns, joins, functions and unknown parameters.London users: estimated 165, really 2,294
5Nested loop for a small outer side, hash join for two big unsorted inputs, merge join for sorted ones; join order is a search, randomised (GEQO) from 12 tables.16-table join: 1,645 ms to plan exhaustively, 21 ms with GEQO
6Read EXPLAIN (ANALYZE, BUFFERS) bottom up; compare estimated with actual rows; count pages.Per-node timing added 67% to one scan
7Find (pg_stat_statements), explain, fix, verify.One query was 78.6% of database time; one index took throughput from 285 to 1,181 transactions a second
8Fixes, in the order to try them: index, rewrite, statistics, application changes.21 queries instead of 1: 6.5 times slower even on one machine; COPY 199 times faster than row-by-row inserts
9A few settings matter: memory per sort or hash, cache size hints, page costs, parallel workers, JIT.Spills to disk cost 1.1 to 1.7 times at the default 4 MB here; 5 parallel workers made a scan 4.6 times faster
10Prepared statements can switch to one generic plan, which can be terrible for unusual parameter values.The same call went from 520 ms to 4,419 ms
11Plans change under you; detect regressions and pin a plan only as a last resort.A pinned plan made the common small-customer call about 180 times slower

The parent's Query plans tab holds seven more measured cases on the same data (sequential against index scan, column order in an index, functions that hide a column, a misestimate fixed by extended statistics, Postgres against DuckDB, index-only scans and VACUUM, cold against warm cache); this page links them where they apply.

1. What a planner does

SELECT * FROM messages WHERE chat_id = 42 ORDER BY created_at says nothing about which file to open, whether to use an index, or in what order to work. SQL is declarative: it describes the result. A chain of components turns it into steps, the same in every relational database (The Path of a Query), five steps from text to rows.

The plan is a tree of nodes. The leaves read data: a Seq Scan reads every page of a table in order; an Index Scan walks an index and fetches each matching row; a Bitmap Heap Scan collects matching row addresses from an index, then reads their pages in physical order; an Index Only Scan answers from the index without touching the table. Nodes above combine rows: the three join algorithms (section 5), Sort, Aggregate, Limit. Each node asks its child for the next row, so a Limit at the top can stop the whole tree early.

The planner cannot try the plans; running them would cost more than the query. For each candidate it estimates each node's cardinality and the cost that follows (section 2), from statistics about the data (section 3), and for joins it searches the explosion of orders cleverly (section 5). Planning takes about a millisecond for the queries on this page, and 1.6 seconds for one 16-table join measured. Every bad plan on this page is a correct choice made on a wrong estimate, or on a cost model that does not match the machine.

The path of every query: five components, the same in every relational database

ParseCheck the grammar and build a tree of the statement.
AnalyseLook up every name: which table is messages, which type is chat_id.
RewriteReplace views by the queries that define them and apply rules.
PlanEnumerate ways to run it, estimate the cost of each, keep the cheapest.
ExecuteRun the chosen plan and stream rows back.

The planner (step 4) is the subject of this page; the plan it hands to the executor is a tree of nodes, read in section 6.

2. How the planner prices a plan

A cost is a number in arbitrary units, not milliseconds: reading one 8 KB page as part of a sequential run costs 1.0 (seq_page_cost), a page reached by jumping to it 4.0 (random_page_cost), handling a row 0.01, an index entry 0.005, evaluating one operator such as <= 0.0025 (Planner cost constants). Random is only 4 times sequential, when on a spinning disk it is closer to 100, because the default assumes most random reads come from memory: random access "is normally much more expensive than four times sequential access", says the documentation (section 9 comes back to this).

Every cost constant and its default (reference)
SettingDefaultWhat it prices
seq_page_cost1.0One page read as part of a sequential run
random_page_cost4.0One page read by jumping to it (an index lookup)
cpu_tuple_cost0.01Handling one row
cpu_index_tuple_cost0.005Handling one index entry
cpu_operator_cost0.0025Evaluating one operator, such as = or <=, once
parallel_setup_cost, parallel_tuple_cost1000, 0.1Starting parallel workers; passing one row from a worker to the leader
effective_cache_size4 GBNot a cost: how much of the data the planner may assume is cached, used when pricing repeated index reads

A sequential scan, priced by hand

SELECT * FROM users WHERE id BETWEEN 5001 AND 25000. The catalogue (pg_class) says users occupies 1,280 pages and holds 100,000 rows. A sequential scan reads every page and checks two comparisons (>= and <=) on every row:

cost = 1,280 × 1.0 + 100,000 × (0.01 + 2 × 0.0025) = 1,280 + 1,500 = 2,780

EXPLAIN prints exactly Seq Scan on users (cost=0.00..2780.00 ...): startup cost 0, total cost 2,780. Startup cost matters when a Limit only wants the first few rows; the hero's slow search turns on exactly that.

An index scan: pages depend on physical order

An index scan pays for the index pages and entries it reads, then one table page fetch per matching row, unless consecutive matches sit on the same page. How often they do depends on the column's correlation, measured by ANALYZE: messages.id has 1.00 (messages were inserted in id order), users.id -0.03 (no useful order) measured. The planner estimates heap pages two ways and interpolates by correlation squared: with no correlation, the Mackert and Lohman approximation of how many distinct pages N random fetches touch in a table of T pages, about 2TN/(2T+N) when the table fits in cache, each at random_page_cost; with perfect correlation, the matching fraction of the table read nearly sequentially (costsize.c, cost_index). A bitmap scan sits between the two: it sorts the matching row addresses by page and visits each page once, priced between random and sequential by how much of the table it touches.

Fig. 2 runs the three paths on the same range, id BETWEEN 5001 AND 25000 on users, with the costs EXPLAIN printed and the pages and times measured (each path forced in turn).

  1. The table and its index. users: 100,000 rows in 1,280 pages of 8 KB (each tile in the figure is 4 pages). Its primary-key index users_pkey is a root page over 276 leaf pages, ids in order. The query wants 20,000 rows.
  2. Seq Scan: every page once, in order. 1,280 sequential pages at 1.0 plus 100,000 rows checked: cost 2,780. Measured: 1,280 pages, 5.4 ms, whatever the range.
  3. Index Scan: descend, then jump for every row. From the root to the leaves that hold the range (about a fifth of the 276), then one table fetch per matching row. With correlation -0.03 the planner expected consecutive ids on scattered pages; in fact these rows sit on 315 pages in long runs (where they sit, and where each jump lands, is drawn for illustration), so the scan fetches the same pages again and again: 19,460 page visits, cost 5,733, 3.4 ms.
  4. Bitmap Heap Scan: collect, sort by page, read each page once. The index hands over 20,000 row addresses; a bitmap sorts them by page; each of the 315 pages is read once in physical order. 375 pages with the index's, cost 2,003, 2.4 ms: the cheapest by both measures, and the planner's choice.
  5. Correlation 1.00: the index scan wins. messages was inserted in id order, so 1,000,000 of its 10,000,000 rows by id sit together, one tenth of the table read as one run: the index scan touched 25,294 pages in 137 ms against 192,356 pages and 659 ms for the Seq Scan.

The calculator: where the winner changes

The figure shows one size; the calculator beside this prices all three paths at any size with the formulas Postgres uses, so the crossovers become visible. Predict first: on users, at how many rows does the bitmap scan stop beating the sequential scan, and does the plain index scan ever win? Then switch to messages, whose rows sit in id order.

What the three paths cost and took at the two default sizes:

QueryPathPlanner costPages touchedTime
20,000 users by id (correlation -0.03)Seq Scan2,7801,2805.4 ms
Index Scan5,73319,4603.4 ms
Bitmap Heap Scan (chosen)2,0033752.4 ms
1,000,000 messages by id (correlation 1.00)Seq Scan342,345192,356659 ms
Index Scan (chosen)51,38425,294137 ms
Bitmap Heap Scan341,12721,977139 ms

Measured: each path forced in turn, serial plans, warm cache, best of three. "Pages touched" counts buffer hits plus reads, so the index scan pays one visit per row fetched even when the next row is on the page it just read. These 20,000 users happen to sit on just 315 of the table's 1,280 pages (it was rewritten earlier in its life), which one correlation number cannot tell the planner, and why the bitmap touched so few. The planner's ranking matched the stopwatch in both cases, and it chose an index scan for up to 6,000,000 of the 10,000,000 messages because the rows it needs sit together.

Defaults reproduce Postgres's own costs, independently
The calculator's formulas, transcribed from the PostgreSQL 16.2 source (cost_seqscan, cost_index, index_pages_fetched, cost_bitmap_heap_scan, genericcostestimate, btcostestimate and the histogram code), reproduce 150 of 150 figures that EXPLAIN printed (row estimates, sequential, index and bitmap costs) across 25 ranges on the two tables, to the cent (checked in src/recompute.py).
What the cost model does not know
Whether a page is already in memory (except through effective_cache_size), how fast your disk is, what else is running, and anything about the data beyond its statistics. It is deliberately crude. Leis and colleagues found on real join queries that the cost model "has much less influence on query performance than the cardinality estimates" (How Good Are Query Optimizers, Really?, PVLDB 2015): get the row counts right and a crude cost model is enough.

Three prices for one range query: the cheapest line wins, and the winner changes at a crossover

Change the cost settings and the correlation (try random_page_cost 1.1, or correlation 1 on users)

The arithmetic of each path at this size
Measured at every size, the in-browser self-check, and the inputs (reference)

Each path forced in turn (enable_seqscan, enable_indexscan, enable_bitmapscan switched off for the others), serial plans (max_parallel_workers_per_gather = 0), warm cache, best of three, measured 2026-10-04 on PostgreSQL 16.2, Apple M1 Pro. Green: fastest. Pages: buffer hits plus reads at the scan node, so a page visited twice counts twice. Statistics as stored when measured (users' id correlation -0.03 although the rows sit in long runs).

Simplifications, all of which also hold for the measured queries: one table, one range condition on an indexed bigint column, no NULLs, both ends of the range inside the histogram (the planner looks up the real minimum and maximum through the index when a bound falls in the first or last bucket, which this calculator does not), serial plans. Parallel plans divide CPU costs among workers and add parallel_setup_cost and parallel_tuple_cost.

3. Statistics: what the planner knows about your data

Every row estimate starts from statistics that ANALYZE computes and stores in the catalogue (the pg_stats view; Statistics Used by the Planner). It reads a random sample of 300 × the statistics target rows, and the target defaults to 100, so about 30,000 rows however big the table is (analyze.c; default_statistics_target). For each column it keeps:

Field in pg_statsMeaningA real value from this database
null_fracShare of rows that are NULL0 for every column here
n_distinctNumber of distinct values; a negative number is a fraction of the rows (-1 means every row differs)users.country: 20; users.email: -1
most_common_vals, most_common_freqsThe most common values (MCV list), up to the target's count, with the share of rows each hasusers.plan: free 0.8495, pro 0.1410, team 0.0095 (true: 0.8482, 0.1415, 0.0103)
histogram_boundsBoundaries that split the remaining values into buckets holding equal numbers of rowsmessages.tokens: 101 bounds after 100 common values
correlationHow closely physical row order follows the column's order (section 2)messages.created_at: 1.00; chats.user_id: -0.003

How the numbers become an estimate

For WHERE country = 'GB' the planner finds GB in the MCV list with frequency 0.0699: 0.0699 × 100,000 = 6,987 estimated; the truth is 6,883 measured. A value not in the list gets an equal share of what the list leaves: (1 − sum of MCV frequencies) / (distinct values − number of MCVs). A range such as tokens < 200 counts the histogram buckets below 200 and assumes values spread evenly inside the bucket where 200 falls (Row Estimation Examples; the calculator in section 2 reproduces this for a range on id). With nothing to go on, such as a function applied to a column, the planner falls back to fixed guesses: 0.5% of the rows for an equality, a third for an inequality (selfuncs.h).

The sample gets common values right, and buckets crowd where values are dense

Distinct counts are the hardest number to sample

A sample cannot count distinct values without guessing how many it missed, and Postgres's estimator guesses low for skewed columns: chats.user_id is stored as 75,971 distinct users when there are 99,945, and messages.chat_id as 872,528 when there are 999,951 measured. Distinct counts drive join estimates (section 4), and Leis and colleagues saw "severe underestimates for large tables" of exactly this statistic (PVLDB 2015, section 3.4). Raise the target per column where it matters, not globally: ALTER TABLE chats ALTER COLUMN user_id SET STATISTICS 1000; then ANALYZE chats;. The cost is ANALYZE time and a slightly slower planner (longer lists to search).

Measured: what raising the statistics target changes (table)
TargetRows sampledANALYZE timen_distinct storedMCVs keptEstimate, busiest user (truth 751)Estimate, a typical user (truth 9)

Measured on a copy of chats (1,000,000 rows), one ANALYZE per target. Sampling is random, so a second run gives slightly different values; at 10,000 the sample is the whole table and the numbers are exact.

Statistics go stale

Autovacuum re-analyzes a table after autovacuum_analyze_threshold + autovacuum_analyze_scale_factor × rows have changed, 50 rows plus 10% by default (autovacuum settings): for a 10-million-row table, a million changes. A bulk load between two analyses is the classic trap, measured on a small table:

Before the load

1,000 rows, user 7 owns 1% of them. ANALYZE. Estimate for WHERE user_id = 7: 10, truth 10.

After loading 999,000 rows, mostly user 7's

No ANALYZE yet. The planner sees from the file size that the table grew and scales up, but still believes user 7 owns 1%: estimate 9,100, truth 899,110 measured; it picks a Bitmap Heap Scan.

After ANALYZE

Estimate 901,100, and a Seq Scan. Both plans took 47 to 49 ms here (the table was in memory); the wrong estimate becomes expensive when a join is sized for 9,100 rows.

So run ANALYZE right after a bulk load or a large delete, and lower the scale factor for big tables that change steadily (ALTER TABLE messages SET (autovacuum_analyze_scale_factor = 0.01)). Since PostgreSQL 18, pg_upgrade keeps statistics across a major upgrade; before it, a freshly upgraded database planned blind until analyzed (PostgreSQL 18 release notes). Vacuum itself belongs to Running Postgres in production.

Extended statistics: facts about pairs of columns

Per-column statistics cannot know that every London user is in Great Britain. CREATE STATISTICS adds an object over several columns, of three kinds (CREATE STATISTICS; Multivariate statistics examples): dependencies (how strongly one column determines another; here {"city => country": 1.000}), ndistinct (how many distinct combinations exist; here 60, not 20 × 60 = 1,200) and mcv (the most common combinations with their frequencies). Each fixes a different query; on a copy of users, estimated rows against the truth measured:

Green: within a factor of 1.5 of the truth. Dependencies know only that city implies country, not which pairs exist, so they make the impossible "GB and Paris" look common (1,813 estimated; for such incompatible conditions "the correct estimate would be zero rows, but that possibility is not considered", says the documentation). Only the MCV kind knows the pair never occurs. The parent's Query plans tab (case 5) shows the same fix changing a join on 10 million messages. Nothing detects related columns automatically: someone must create the object.

4. Why estimates go wrong

Every misestimate on this page comes from one of four places. In each, the planner did the arithmetic right on an assumption the data broke.

  1. Independence. Conditions on two columns are multiplied as if unrelated. GB is 7% of users and London about 2.3% of all users, so the planner computes 0.07 × 0.023 × 100,000, about 160 rows, when every London user is British and the truth is 2,294. Fix: extended statistics (section 3), or, when the columns are really one fact, one column.
  2. Joins. Errors multiply up the tree, and Postgres keeps no statistics about join results. For an equality join it estimates rows(A) × rows(B) / max(distinct values on each side), assuming every value on the smaller side finds partners. A 10 times error at the bottom of a three-join plan can be 1,000 times at the top. Leis and colleagues built the Join Order Benchmark (113 queries over 21 tables of real IMDb data) to measure this in five systems: "all estimators routinely produce large errors", misestimates "by a factor of 1000 or more" were routine, and the systematic tendency is to underestimate (PVLDB 2015). Underestimates are the dangerous direction: an overestimate wastes a little memory, an underestimate picks an algorithm meant for small inputs, usually a nested loop that blows up.
  3. Expressions, patterns and functions. WHERE lower(email) = ... or WHERE created_at::date = ... have no statistics, so the planner uses its fixed guesses. LIKE 'Chat 123456%' is estimated from the histogram plus a guess for the rest of the pattern: 100 rows against 1 real, the overestimate that makes section 7's search slow. An index on the expression gives the planner statistics as well as a fast path; CREATE STATISTICS on a single expression (PostgreSQL 14 and later) collects the statistics without maintaining an index. Sargability, the rule that an index helps only when the column is left bare, is the parent's Query plans case 3.
  4. Unknown parameters. A plan made before the value is known must guess: a generic plan for WHERE org_id = $1 uses the average share of a non-common value, 290 rows, which for the one organisation owning half the table is wrong by 6,897 times. Section 10 measures what follows.

Five estimates from this database: the gap between the dot the planner believed and the dot that happened

Rows on a log scale. Independence: users in GB and London, estimated 165, actual 2,294. Pattern: titles LIKE 'Chat 123456%', 100 against 1. Stale statistics: after a bulk load, 9,100 against 899,110. Join: London users joined to their chats (the Plan reading lab), 1,580 against 22,364. Unknown parameter: the generic plan for the enterprise organisation, 290 against 2,000,231, off by a factor of 6,897.

The habit that finds all four
Run EXPLAIN (ANALYZE, BUFFERS), walk the plan from the bottom and compare rows= (estimated) with actual rows= × loops at each node. The lowest node where they differ by more than about 10 times is where the plan went wrong; everything above it was planned for the wrong input. Section 6 steps through a real plan this way.

5. Joins: three algorithms, and the order to join in

Postgres has three join algorithms and prices all three (Planner/Optimizer). On the chat data, the planner's choice against the next best plan once that choice is switched off measured:

Nested loop. For each outer row, look up its partners on the inner side, ideally through an index. Wins when the outer side is small. One user's 25 chats with message counts: 25 lookups in the (chat_id, created_at) index, 112 pages, 0.227 ms; forced to hash, all 10 million messages stream past the 25 chats: 192,491 pages, 383 ms.

Hash join. Build a hash table from the smaller input (in work_mem × hash_mem_multiplier), stream the bigger one past it once. Wins when both sides are large and unsorted. All 1,000,000 chats with their users, counted by country: 10,644 pages, 95.4 ms; as a nested loop, 1,000,000 lookups into users (a Memoize node caching repeats): 1,077,750 page visits, 352 ms.

Merge join. Walk two inputs sorted on the join key side by side, like a zipper. Wins when both are already sorted (by an index or an earlier sort), and can stop early under a Limit. The first 1,000 chats in id order with message counts: 48 pages, 1.53 ms; forced to a nested loop, 1,003 separate index descents, 3,053 pages, 2.18 ms.

The planner chooses between them on row estimates, which is where section 4 bites: an underestimated outer side makes a nested loop look cheap, and the inner side then runs once per real outer row. In EXPLAIN that shows as an inner node with loops= in the thousands or millions (section 10 has one with 2,000,231).

Each algorithm wins where its shape fits: a small outer side, two big unsorted inputs, two inputs already sorted

Nested loop
Hash join
Merge join

Measured by the parent's Query plans tab (case 4) on the same data, PostgreSQL 16.2, Apple M1 Pro, 2026-10-04, median of 5 runs; pages are buffer hits plus reads over the whole plan. Forced with SET enable_nestloop = off (or enable_hashjoin, enable_mergejoin): diagnostic switches for a session, never a production fix, since they make that plan type look absurdly expensive for every query. In the sorted case both plans stop after 1,000 chats, so the gap is small; the planner had costed them at 604 and 1,006.

Join order is a search

With n tables there are n! orders for a simple chain of joins (3,628,800 for ten), more if intermediate results may themselves be joined ("bushy" trees). Since IBM's System R (Selinger and colleagues, Access Path Selection in a Relational Database Management System, SIGMOD 1979) planners use dynamic programming: find the cheapest way to join every pair, keep it, build the cheapest plan for every set of three from the kept pairs, and so on. That turns the factorial into "only" exponential, because it still visits every subset of tables the join conditions connect.

Postgres runs this near-exhaustive search while the FROM list has fewer than geqo_threshold (12) items. From 12 on it switches to GEQO, which treats join order like the travelling salesman problem: it encodes orders as strings such as 4-1-3-2, breeds and mutates a population of them, and keeps the cheapest found in a fixed budget (GEQO in PostgreSQL). It is randomised (the result depends on geqo_seed) and need not find the best plan.

When to act: generated queries joining 12 or more tables (ORMs, BI tools). Read the planning time in EXPLAIN's summary; raise geqo_threshold only if planning stays affordable, or split the query.

Exhaustive planning time explodes with tables; GEQO stays flat

Two subtleties: JOIN syntax limits the search, and exhaustive is not the same as right (depth)

Explicit JOINs are reordered only in groups of 8. join_collapse_limit and from_collapse_limit (8 by default) stop the planner from flattening longer chains of JOIN ... ON or nested subqueries into one search, so a 14-table query written with JOIN syntax is planned as smaller searches whose boundaries follow how you wrote it, and GEQO never runs; written as a comma-separated FROM list it is one search of 14 items and GEQO does (Controlling the Planner with Explicit JOIN Clauses).

Exhaustive is not the same as right. The search is only as good as its row estimates, which can be off by 1,000 times on joins. Leis and colleagues still found exhaustive dynamic programming beat heuristic search on their benchmark, despite the bad estimates.

6. Reading EXPLAIN like a professional

EXPLAIN shows the chosen plan without running it. EXPLAIN ANALYZE runs the query (so it really inserts, updates or deletes: wrap those in BEGIN; ... ROLLBACK;) and adds what happened (EXPLAIN; Using EXPLAIN). Plain EXPLAIN shows only estimates, so it cannot show the misestimate that is usually the cause: use EXPLAIN (ANALYZE, BUFFERS) by default (PostgreSQL 18 turns BUFFERS on automatically with ANALYZE).

Other EXPLAIN options worth knowing (SETTINGS, VERBOSE, FORMAT JSON, GENERIC_PLAN, SUMMARY)

SETTINGS (lists settings changed from their defaults, so a plan pasted into a ticket says which work_mem it ran with), VERBOSE (output columns), FORMAT JSON (for explain.dalibo.com and explain.depesz.com), GENERIC_PLAN (PostgreSQL 16+: the plan for a statement with $1 placeholders) and SUMMARY (planning time).

One node, field by field

->  Index Scan using chats_pkey on chats  (cost=0.42..37801.43 rows=100 width=19) (actual time=11.819..91.565 rows=1 loops=1)
      Filter: (title ~~ 'Chat 123456%'::text)
      Rows Removed by Filter: 999999
      Buffers: shared hit=12053
Index Scan using chats_pkey on chats
The node type, the index it walks, the table it reads.
cost=0.42..37801.43
Estimated startup and total cost, in the units of section 2.
rows=100
Estimated rows this node will output (per loop).
width=19
Estimated average bytes per output row.
actual time=11.819..91.565
Milliseconds until the first and the last row, per loop, including everything below this node.
rows=1 loops=1
Actual rows per loop, and how many times the node ran. Total rows = rows × loops; total time is roughly time × loops.
Filter, Rows Removed by Filter
A condition checked on each row after fetching it, and how many rows it threw away; a large number is wasted work. An Index Cond instead would mean the index did the filtering.
Buffers: shared hit=12053
8 KB pages found in Postgres's buffer pool (hit), asked from the operating system (read, which may still come from its memory), modified (dirtied) or written out to make room (written); temp pages are sorts and hashes that spilled (section 9).

This is the hero's node: the planner expected 100 matching titles and, walking the primary key in id order, expected to find the first 10 after about a tenth of the table (cost 3,780 at the Limit above it). There was 1 match, so it read all 1,000,000 rows. The estimate (100) against the actual (1) is the whole diagnosis.

Reading a whole plan

Start at the bottom (the most indented lines) and go up; at each node compare estimated rows with actual rows × loops; the lowest big mismatch is the cause. Fig. 3 steps through a real plan from this database, the five London users with the most chats; the plan text under the steps is what EXPLAIN printed, with each step's lines marked.

  1. A real plan, as EXPLAIN prints it. The most indented lines run first and pass rows up, so read it from the bottom. In the figure each node carries two bars on a log scale: glass for the rows it estimated, solid for the rows it produced (actual rows × loops).
  2. The bottom: Seq Scan on lab_users. Estimated rows=158, actual rows=2,294: 14.5 times under. The planner multiplied the share of GB users by the share of London users as if the two were independent (section 4). This is the lowest big mismatch, so it is the cause.
  3. The inner side: Index Only Scan on chats. Estimated 13 rows per loop, actual 10 per loop: fine for each lookup. But loops=2,294 where the plan expected 158: a nested loop was chosen for a small outer side that was not small.
  4. Nested Loop: inherited, not new. rows=1,580 estimated, 22,364 actual: about 158 × 10 against 2,294 × 10. The error came up from the scan below.
  5. HashAggregate: inherited again. 158 groups expected, 2,291 found (one per London user with chats). It still fitted in memory: Batches 1.
  6. Sort and Limit: the answer, and the bill. 5 rows, as asked, in 14.364 ms. Fast here, because 2,294 lookups are cheap; the same underestimate on a bigger table sends a nested loop into millions of lookups.
  7. The fix, and the plan it produces. CREATE STATISTICS ... (dependencies, mcv) ON country, city FROM lab_users; ANALYZE lab_users; Now the scan estimates 1,335 rows per process against 1,147 actual (two processes), every bar above it matches, the planner adds a parallel worker (a Gather node), and the query takes 10.566 ms.

Real EXPLAIN (ANALYZE, BUFFERS) output on a copy of users (lab_users) joined to chats, PostgreSQL 16.2, 2026-10-04. Before the fix: Seq Scan on lab_users estimated rows=158 against actual rows=2294; the Nested Loop rows=1580 against 22364; Execution Time 14.364 ms. After CREATE STATISTICS on (country, city): 1,335 estimated per process against 1,147 actual, a parallel plan, 10.566 ms. The same plan is exercise 3 of the Plan reading lab.

Two more things to read: time and pages (a node's time includes its children, so subtract them, and multiply by loops; pages, unlike milliseconds, do not change between a cold and a warm run, the parent's Query plans case 8), and waste: Rows Removed by Filter in the millions, Heap Fetches on an Index Only Scan (the table was visited after all), Sort Method: external merge or Batches above 1 (spilled), Workers Launched below Workers Planned (no free parallel workers), and Planning Time against Execution Time (for short queries run thousands of times, planning can be most of the cost; section 10).

Every common node in one table (reference)
NodeWhat it doesWorth noticing
Seq Scan / Parallel Seq ScanReads every page of a tableFine for small tables or when most rows match; a Filter removing nearly everything suggests an index
Index Scan (Backward)Walks an index in order and fetches each matching rowDelivers rows sorted by the index, which can make a Sort unnecessary
Index Only ScanAnswers from the index aloneHeap Fetches counts rows it still had to check in the table, because the visibility map was out of date (VACUUM sets it)
Bitmap Index Scan + Bitmap Heap ScanCollects matching row locations, then reads pages in physical orderHeap Blocks: exact=, lossy=: lossy pages (when the bitmap outgrows work_mem) must recheck every row; Recheck Cond
Nested LoopFor each outer row, runs the inner sideInner loops= is the number of outer rows; great when that is small, terrible when an underestimate made it large
Hash Join + HashBuilds a hash table from one input, streams the other past itBatches above 1 means the hash table spilled to disk
Merge JoinZips two inputs sorted on the join keyOften fed by Sort nodes or index scans
MemoizeCaches inner results of a nested loop by key (PostgreSQL 14+)Hits and Misses show whether the cache helped
Sort, Incremental SortOrders rows; incremental sort finishes an order that is already partly thereSort Method: quicksort Memory (fine), top-N heapsort (a Limit above), external merge Disk (spilled)
HashAggregate, GroupAggregate, AggregateGROUP BY with a hash table, over sorted input, or one group for the whole inputHashAggregate Batches above 1 means it spilled
Gather, Gather MergeCollects rows from parallel workersRows and times below it are per process: multiply by loops
LimitStops after n rowsMakes startup cost matter; a plan chosen "because it can stop early" is fragile when matches are rarer than estimated
Materialize, CTE Scan, SubPlanStores an intermediate result; a SubPlan runs once per outer rowA SubPlan with large loops is a correlated subquery that a join might replace
Append, Result, ProjectSetConcatenates inputs (UNION ALL, partitions); computes expressionsAppend over partitions shows which ones were pruned

What measuring costs

EXPLAIN ANALYZE reads the clock twice per row per node. On this laptop a clock read costs 20.6 nanoseconds (pg_test_timing), and SELECT count(*) FROM messages took 432 ms plainly, 722 ms under EXPLAIN ANALYZE and 469 ms with TIMING OFF measured: per-node timing added 67% to a query pushing 10 million rows through two nodes. Row counts and buffers stay exact either way, so use (ANALYZE, BUFFERS, TIMING OFF) when counts are enough, and trust ratios rather than absolute times from a timed plan. The same cost applies to auto_explain (section 7), which is why its log_timing is often switched off.

Practise: the Plan reading lab tab has eight real plans from this database, each with a question to answer by clicking a line of the plan, and the answer with its explanation.

7. The slow-query workflow: find, explain, fix, verify

"The app is slow" is not a query. Do not start by staring at the query you suspect: ask the database which statements consume its time, explain the top one, change one thing, and measure again under the same load. Four steps, each with a standard tool.

Find: pg_stat_statements

pg_stat_statements, an extension shipped with Postgres and loaded at server start, keeps running totals for every distinct statement (pg_stat_statements). It normalises them, so WHERE chat_id = 42 and = 77 become one entry, WHERE chat_id = $1, with calls, total and mean time, rows and pages, for up to 5,000 statements by default. Ask it which statements use the most total time, because that is what the server spends and what users wait behind:

SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time, 2) AS mean_ms,
       round(100 * total_exec_time / sum(total_exec_time) OVER (), 1) AS pct, query
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;

A query that takes 2 ms but runs 50,000 times an hour costs more than a 30-second report run once a day. Sorting by mean time answers a different question: what users of one page feel.

Explain: get a real plan with real values

pg_stat_statements has only $1; a plan needs a real value. log_min_duration_statement logs the text and duration of any statement slower than a threshold (logging settings), and the auto_explain extension logs its plan too (auto_explain). With both at 20 ms during the replay below, the log held measured:


The logged plan is the one that actually ran when it was slow, which matters for problems that come and go (section 10). The price: with auto_explain.log_analyze on, every statement is timed per node whether or not it is logged, which the documentation warns "can have an extremely negative impact on performance"; turn log_timing off (as here) and sample with auto_explain.sample_rate.

Fix one thing, then verify under the same load

Change one thing (section 8), SELECT pg_stat_statements_reset();, replay the same load, compare. Load catches what one EXPLAIN cannot: a new index slows every write, and removing the top query moves the bottleneck to the next.

Sorting by total time finds the query nobody complained about

1 Find
2 Explain
3 Fix
4 Verify

The whole routine on one workload

The replay: pgbench, Postgres's benchmarking tool, runs six of the chat product's queries with random parameters from 4 concurrent clients, 1,000 transactions each, weighted like a day of traffic (opening a chat 40, the sidebar 25, login 20, title search 8, usage totals 6, the weekly report 1). Fig. 4 follows it through the four steps; the toggle runs the same replay through the method it replaces, fixing the query someone complained about. Predict first: which of the six uses the most database time?

  1. The replay. pgbench runs the six queries from 4 clients, 1,000 transactions each, with random parameters: 285 transactions a second, 14.0 ms average latency. Something is slow; nobody knows what.
  2. Find: rank statements by total time. pg_stat_statements after the replay, sorted by total_exec_time: one statement, the title search, used 78.6% of all database time.
  3. Find: why total time, not the slowest call. The search ran 331 times at 112.9 ms: 37,380 ms of the 47,575 ms total. Opening a chat ran 4.7 times more often but cost 28 times less per call.
  4. Explain: get a real value from the log. pg_stat_statements shows LIKE $1 || $2 || $3, with no values; log_min_duration_statement (20 ms here) logged real calls, such as the one in the panel, which took 367.7 ms under load.
  5. Explain: EXPLAIN (ANALYZE, BUFFERS). Estimated rows=100, actual rows=1, and 999,999 rows removed by the filter: the planner walked the primary key expecting to find 10 matches early. The Limit trap (Fig. 1).
  6. Fix: one index. CREATE INDEX chats_title ON chats (title), built in 1.4 s, 31.6 MB. With the C collation a B-tree serves LIKE 'prefix%' as a range.
  7. Fix: the new plan. An Index Cond turns the prefix into a range on title, 7 pages instead of 12,053: 0.078 ms for the same search.
  8. Verify: same replay, statistics reset. Throughput 285 to 1,181 transactions a second (4.1 times), average latency 14.0 to 3.39 ms. The search fell to 0.7% of database time.
  9. And again. The top of the list is now opening a chat (32.2%), a 2 ms query run 1,554 times. The routine repeats until the top entry is something you accept.

Measured with pg_stat_statements, auto_explain and pgbench from the same PostgreSQL 16.2 build (all three compiled from the 16.2 source for this page, since the Python wheel used for the database ships without them). Times on a shared laptop vary; the other queries' means moved between the two replays because the title search had been holding pages and CPU. The hunch's "at most 2.5%" is derived: the report's share of database time (2.4%) is the most that making it free could remove, which raises throughput by 1 / (1 − 0.024) − 1.

Why this query was slow, and the two fixes
The search WHERE title LIKE 'Chat 123456%' ORDER BY id LIMIT 10 fell into the Limit trap: estimating 100 matching titles, the planner walked the primary key in id order to stop after 10 (cost 3,780 against sorting all matches). With one match, every search read the whole table through the index: 12,053 pages, 91.6 ms in EXPLAIN, 112.9 ms on average under load. An index on title turns LIKE 'prefix%' into a range scan (this database uses the C collation; otherwise create it with text_pattern_ops, Operator Classes): 0.078 ms, about 1,170 times faster, for 31.6 MB and slower inserts into chats. Without an index, ordering by title removes the temptation to walk the primary key: a parallel scan and a sort of the one match, 33 ms instead of 84 ms measured, still a full scan per keystroke. A substring LIKE '%123456%' cannot use a B-tree at all; it needs a trigram index (pg_trgm, on Search and vector databases).

8. The fixes, in the order to try them

Once the plan shows the cause, the fix usually comes from this list, in order of how often it is the answer and how little it risks.

1. An index, or a better one

When: the query reads far more rows than it returns (large Rows Removed by Filter, a Seq Scan feeding a small result). How: a B-tree on the columns it filters, joins or sorts on (Indexes), in four variations: a composite index, equality columns first and the range or sort column last (the parent's Query plans case 2); an expression index such as ON users (lower(email)) (case 3); a partial index such as ON jobs (created_at) WHERE status = 'pending', small because it covers only the rows the query wants (Partial Indexes); and a covering index, ON chats (user_id) INCLUDE (title), which can answer from the index alone (an Index Only Scan, case 7; Index-Only Scans and Covering Indexes). Cost: space (the title index: 31.6 MB for a million rows, built in 1.4 s measured), and every insert, and every update of an indexed column, writes one more structure. Not: where most rows match, on tables written far more than read, or twice on the same columns (find unused ones with pg_stat_user_indexes.idx_scan = 0 over a business cycle). Build with CREATE INDEX CONCURRENTLY in production. Index structures are Storage engines and indexes's subject.

2. Rewrite the query

The SQL asks for something the planner cannot do cheaply, or hides information from it. The rewrites that come up again and again:

  • Leave indexed columns bare: created_at >= '2026-03-01' AND created_at < '2026-03-02', not created_at::date = '2026-03-01' (case 3).
  • Avoid the Limit trap: ORDER BY x LIMIT n with a rare filter on another column (section 7).
  • Replace a per-row subquery with a join: a SubPlan with loops= in the thousands runs once per outer row; a join or LEFT JOIN LATERAL runs once (the Plan reading lab has one).
  • NOT EXISTS, not NOT IN, for "rows with no match": NOT IN returns nothing if the subquery yields a NULL, and it cannot be planned as an anti-join (Subquery Expressions).
  • Select the columns you need: narrower rows, and index-only scans become possible.
  • Paginate by key, not by OFFSET, below.

Test that a rewrite returns the same rows.

Pagination: OFFSET reads every row it skips

ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET 500000 makes the database produce 500,020 rows and throw 500,000 away. A keyset (cursor) page remembers the last row's sort key instead and seeks straight to it: WHERE (created_at, id) < (:t, :id) ORDER BY created_at DESC, id DESC LIMIT 20, with an index on (created_at, id). Predict the cost of page 25,001 under each, then compare with the chart.

The trade: a keyset page cannot jump to page 7, and the sort key must be unique (add the id as a tiebreaker). How the API exposes it (opaque cursors, filters that change between pages) belongs to Service APIs.

OFFSET grows in proportion to the depth; a keyset page costs the same at every depth

One 20-row page from a 1,000,000-row table, PostgreSQL 16.2, EXPLAIN (ANALYZE, BUFFERS) execution time, median of 7 runs, warm cache, 2026-10-04 on an Apple M1 Pro, recorded by the Building a backend API page's script. At depth 500,000: OFFSET 98.1 ms and 17,544 pages, keyset 0.032 ms and 4 pages; the keyset page stayed between 0.023 and 0.044 ms from the first page to a million rows deep, an index descent of a few pages. The cost of OFFSET is linear in the rows skipped: 98.1 ms / 500,000 rows, about 0.2 microseconds a row here (derived).

3. Give the planner better statistics

Section 3: ANALYZE after bulk changes, a higher target on skewed columns, extended statistics for related columns, an expression index or expression statistics for computed predicates. Cheap and safe; it fixes estimates, not missing access paths.

4. Change how the application talks to the database

Many "slow database" problems are too many round trips. Measured from Python (psycopg 3.3.6) over TCP on the same laptop, the cheapest round trip there is (0.056 ms for SELECT 1).

N+1 is what an ORM (SQLAlchemy, Django's ORM, ActiveRecord) does with lazy loading: one query for a user's 20 chats, then one per chat for its last message, 21 round trips, where one query with LEFT JOIN LATERAL returns the same 20 rows. On one machine: 1.42 ms against 0.22 ms per page, 6.5 times; across a network each extra trip adds its full latency, and the Numbers to know tab of Topic: swe-and-system-design works the same 21 queries at a 2 ms zone-to-zone round trip into 43 ms. The fix is eager loading (selectinload or joinedload in SQLAlchemy, select_related and prefetch_related in Django); N+1 is invisible in the code that causes it, so count queries per request with SQL logging on in development. Structuring the handler is Building a backend API's subject. Batching is the same idea for writes: 10,000 single-row INSERTs, each its own transaction, took 1,391 ms; COPY took 7.0 ms, 199 times faster, because each commit waits for the log to reach disk and each statement is a round trip. Larger batches hold locks longer and fail as a unit.

Round trips, not queries, are the cost: 21 queries against 1, and 10,000 inserts six ways

Connections: a pool, not more connections

Each Postgres connection is an operating-system process, so opening one costs a process start and authentication. Measured on Running Postgres in production with pgbench, 8 clients running SELECT 1.

The second question is how many connections should be active at once. Beyond roughly the core count, more concurrent queries add contention for CPU, locks and the buffer pool, not throughput: latency rises while throughput stays flat. The PostgreSQL wiki's starting point is about (2 × CPU cores) + number of disks active connections (Number Of Database Connections; a point to measure from, not a law); Andres Freund found the cost of many connections was CPU, every snapshot scanning the list of connections, which PostgreSQL 14 made much cheaper (Analyzing the limits of connection scalability in Postgres). So: a small pool per application process behind a pooler in transaction mode, with excess requests waiting in the pool's queue (on the same page, 1,000 clients through PgBouncer reached Postgres as 20 server connections). Pool sizing with Little's law is on Capacity planning and performance; PgBouncer's modes and how transaction pooling breaks session state, on Running Postgres in production.

A new connection per transaction costs 53 times the throughput; a pooler recovers part of it

PostgreSQL 16.2 and PgBouncer 1.24.1 on the same Apple M1 Pro, 2026-10-05; "new connection each time" is pgbench -C: connect, one query, disconnect, which is what an application without a pool, or a serverless function, does. Direct: 87,487 against 1,660 transactions a second; through PgBouncer: 32,093 against 9,337 (the extra hop costs on persistent connections, and saves the process start on new ones).

5. Settings, then hardware, last

Section 9. A setting changes every query on the server, so it fixes one query only by accident; hardware multiplies whatever the queries do, waste included. Both come after the query is right.

9. The settings that matter

This PostgreSQL 16.2 server has 384 settings (SELECT count(*) FROM pg_settings, extensions included); a handful decide query performance (Resource Consumption, Query Planning). Most can be set per database, role, session or transaction (SET LOCAL) as well as server-wide.

SettingDefaultWhat it doesCommon practice
shared_buffers128 MBPostgres's own page cache (the buffer pool)The documentation's starting point is 25% of RAM on a dedicated server, and "unlikely" to help beyond 40%, because Postgres also relies on the operating system's cache
effective_cache_size4 GBAllocates nothing: tells the planner how much of the data is likely cached, which makes repeated index reads look cheaperRoughly shared_buffers plus the operating system cache you expect Postgres to get, often half to three quarters of RAM
work_mem4 MBMemory for each sort or hash operation before it spills to temporary files; hashes may use hash_mem_multiplier (2.0) times moreRaise per role or per session for reports; keep the server default modest (below)
random_page_cost4.0Price of a random page read (section 2)Lowered on fast or fully cached storage, after measuring (below)
max_parallel_workers_per_gather2Workers one parallel step may useRaised for analytics, kept low for many small concurrent queries
jitonCompiles expressions to machine code for expensive queriesOften left on for analytics, switched off for short transactional queries (below)

work_mem, and what a spill costs

A sort or hash that needs more than work_mem writes partial results to temporary files and reads them back: the Sort becomes external merge, the Hash and HashAggregate split into Batches. Measured on three queries at five settings (serial plans, best of three).

The penalty is smaller than folklore suggests because the temporary files never left the operating system's memory on a laptop with free RAM and a fast SSD; on network-attached cloud disks or a memory-starved server it is larger. The bigger danger is the other direction. work_mem is per operation, per process: the documentation warns that "the total memory used could be many times the value of work_mem". A query with three sorts, run by 200 connections at 256 MB each, could ask for 150 GB. So keep the default modest, raise it where it pays (ALTER ROLE reporting SET work_mem = '256MB', or SET LOCAL inside one transaction), and find spills with log_temp_files = 0 or pg_stat_statements' temp_blks_written. Sizing work_mem with the other memory settings for a whole server is Running Postgres in production section 1.

At the default 4 MB all three spill, and here a spill cost 1.1 to 1.7 times

random_page_cost on SSDs

Correction to the old page
The old page said a random_page_cost of 4 "pushes the planner towards sequential scans" on NVMe and that 1.1 "is the common setting". The current documentation gives no SSD value: 4 is already low because "the majority of random accesses to storage, such as indexed reads, are assumed to be in cache", and it suggests lowering it when the data is likely fully cached or network latency is high (random_page_cost). 1.1 is a widespread practice, not a documented standard. The parent's Query plans case 4 shows 1.1 changing a real plan; the calculator in section 2 moves the crossover. Change it, like every piece of folklore (huge work_mem, JIT on or off), one setting at a time with before and after numbers from your own workload.

Parallel query

For a big scan, Postgres can start parallel workers, extra processes that each scan part of the table, with a Gather node combining their rows (How Parallel Query Works). The planner picks the number of workers from the table size: one worker for a table of min_parallel_table_scan_size (8 MB), one more each time the table triples (allpaths.c). For the 1.5 GB messages table that is 5, capped by max_parallel_workers_per_gather.

Parallelism splits the work, it does not reduce it: six processes (five workers and the leader) shared the scan. Right for one big report, wrong for a server busy with hundreds of small queries, where workers compete for the same cores. Queries that write data or lock rows never run in parallel (When Can Parallel Query Be Used?), and workers come from a fixed pool (max_worker_processes, max_parallel_workers, 8 each by default), so Workers Launched can be lower than planned at busy times.

Five workers made the scan 4.6 times faster, using six cores to do it

JIT compilation: why short queries often run better with jit = off (not measured here)

Since PostgreSQL 11 the server can compile a query's expressions to machine code with LLVM, on by default since version 12; it triggers when the estimated cost exceeds jit_above_cost (100,000), with more aggressive inlining and optimisation above 500,000 (JIT decision). The documentation's own caveat: "for short queries the added overhead of performing JIT compilation will often be higher than the time it can save". Because the threshold is a cost, not a time, a fast query with a large estimated cost (a misestimate, or a big table scanned with a Limit) can pay compilation on every run; that shows up as a JIT: block at the end of EXPLAIN ANALYZE with its timings, and the usual fix for transactional workloads is jit = off for the application's role. Not measured here: the server build used for this page has no LLVM (pg_jit_available() returns false).

10. Prepared statements: one plan for every parameter

A prepared statement is parsed once and then executed many times with different parameter values: PREPARE q(int) AS SELECT ... WHERE org_id = $1; then EXECUTE q(42); in SQL, or the same thing done invisibly by a driver over the protocol. It saves parsing and planning on every call and keeps values apart from SQL text (safe from injection). Postgres can make a custom plan for each call, knowing the value, or reuse one generic plan built without it. The rule, from the documentation: "the first five executions are done with custom plans and the average estimated cost of those plans is calculated. Then a generic plan is created and its estimated cost is compared to the average custom-plan cost", and the generic plan is used from then on if it is not much more expensive (PREPARE).

Drivers do it for you: psycopg 3 prepares a statement on the server after 5 runs on a connection (prepare_threshold, read from a live connection for this page; psycopg: prepared statements), PgJDBC at its prepareThreshold of 5 (PgJDBC), and PgBouncer passes them through in transaction mode when max_prepared_statements is non-zero (PgBouncer configuration). So the generic-plan switch happens in ordinary code, on the sixth call or later: "fast in testing, slow in production".

A regression, measured

The page adds one table to the chat product: usage_events, one row per model call billed to a customer organisation, 4,000,000 rows. One enterprise customer, organisation 1, owns half of them (2,000,231 rows); the other half is spread over 20,000 organisations of about 100 rows each illustrative skew, real measurement. The billing page runs, through a prepared statement, SELECT c.model, count(*), sum(e.tokens) FROM usage_events e JOIN chats c ON c.id = e.chat_id WHERE e.org_id = $1 GROUP BY c.model. Eight calls in one session: five small organisations, the enterprise twice, one small one.

What happened, from the plans: calls 1 to 5 got custom plans for about 100 rows each (an index lookup and a nested loop, cost 1,765, under 1 ms). Call 6, the enterprise, still got a custom plan, a parallel hash join priced at 94,481, which took 520 ms. That expensive call pulled the average custom cost up to 17,218, and the generic plan, which assumes a typical organisation has 290 rows, cost only 3,483. So from call 7 Postgres used the generic plan: a nested loop doing 2,000,231 index lookups into chats, 4,419 ms for the enterprise, 8.5 times its custom plan. The generic plan is fine for everyone else (call 8: 0.53 ms), which is exactly why it looked cheap.

From call 7 Postgres reused one generic plan, and the enterprise call took 8.5 times longer

Fix 1: custom plans for this statementSET plan_cache_mode = force_custom_plan for the session or role that runs it; planning costs about a millisecond here, against seconds saved. Measured: enterprise 531 to 597 ms on every call.
Fix 2: do not prepare itpsycopg prepare=False on that call, or prepare_threshold=None on the connection.
Fix 3: separate the outlierA separate code path or query for the few giant tenants, so one plan fits each group.
See it comingEXPLAIN (GENERIC_PLAN) (PostgreSQL 16+) shows the generic plan; pg_prepared_statements counts generic and custom plans per statement.

11. Plan regressions, and pinning a plan

A plan regression is a query that was fast and became slow without its SQL changing. The plan changed because one of its inputs did: new statistics after ANALYZE, data growth crossing a cost crossover (section 2 shows how sharp they are), a setting, an index added or dropped, a parameter value (section 10), or a major-version upgrade that taught the planner something new (PostgreSQL 18 added B-tree skip scan, for example).

Detecting them is section 7's workflow run continuously: snapshot pg_stat_statements and alert when a statement's mean time jumps (same queryid, new timing; a rising stddev_exec_time means a plan that differs by parameter); keep auto_explain on with a threshold so the bad plan is in the log; before a major upgrade, compare the top statements' plans on a staging copy.

Responding follows section 8's order: fix the estimate (statistics), then the query or index, and only then pin. Core Postgres has no plan pinning, by design: the project's stated position is that it is "not interested in implementing hints in the exact ways they are commonly implemented on other databases" (PostgreSQL wiki: Optimizer Hints). The tools are outside it, chiefly the pg_hint_plan extension, which forces scan methods, join methods and join order from a comment such as /*+ HashJoin(e c) SeqScan(e) */:

The pinning tools: pg_hint_plan, Aurora's plan management, SQL Server's Query Store, Oracle's SQL Plan Management (reference)
  • pg_hint_plan, an extension that reads hints from a comment at the start of the query, such as /*+ HashJoin(e c) SeqScan(e) */, or from a table of hints keyed by query text, and forces scan methods, join methods and join order (pg_hint_plan; this page built its REL16_1_6_1 release).
  • On Amazon Aurora PostgreSQL, apg_plan_mgmt ("query plan management") captures plans and enforces approved ones (AWS documentation). Other databases build this in: SQL Server's Query Store can force a plan, Oracle has SQL Plan Management.

The measured warning is section 10's third toggle: pinning the billing query to a hash join with a sequential scan, the right plan for the enterprise, made each small organisation's call take 105 to 124 ms instead of under 1 ms, about 180 times slower, because each now scans all 1,000,000 chats to probe a hash table of 100 rows; and the enterprise still took 1,133 ms, because the hint fixed the join method but not which side to hash, and the planner hashed the 2,000,231 usage rows instead of the 1,000,000 chats. A pinned plan is right for one range of data and parameters and stays pinned when they move. Keep pins few, written down, and reviewed after every upgrade.

What professionals set up before anything is slow

The routine only works if the evidence is already being collected when the problem appears. A common starting point for a Postgres server, each line from the documentation linked above; the thresholds are judgement calls, not standards:

# postgresql.conf (server restart needed for shared_preload_libraries)
shared_preload_libraries = 'pg_stat_statements,auto_explain'
pg_stat_statements.max = 10000        # default 5000; more if the app sends many distinct statements
track_io_timing = on                  # I/O time in EXPLAIN and pg_stat_statements; check the clock cost with pg_test_timing first
log_min_duration_statement = '500ms'  # log text and duration of slow statements
auto_explain.log_min_duration = '1s'  # and the plan of very slow ones
auto_explain.log_analyze = on
auto_explain.log_buffers = on
auto_explain.log_timing = off         # avoid the per-node clock cost (section 6)
auto_explain.sample_rate = 0.1        # explain one statement in ten
log_temp_files = 0                    # log every spill to disk, with its size
  • Look weekly, not only during incidents: the top 10 statements by total time, and what changed since last week. Many teams keep snapshots of pg_stat_statements in a table or in their monitoring system, since its counters are cumulative and reset on restart or pg_stat_statements_reset().
  • Set a statement_timeout per application role, so one runaway query cannot hold a connection and its locks for an hour (operational detail on Running Postgres in production).
  • Test plans on production-sized data, or at least with production statistics: a plan on a 1,000-row development table says nothing about the 10-million-row one (a Seq Scan is the right plan for a small table and the wrong one for a big one).
  • Tie database time to requests: tracing that shows how many queries each API request made and how long each took is how N+1 patterns get noticed (Observability).
  • Put the index next to the query in code review: a new query on a large table comes with its EXPLAIN output, and a new index with the query that needs it.

Learned optimizers

Where research is (October 2026): Neo, Bao, Balsa and QORL, with a correction (depth; none of it ships in PostgreSQL)

Section 4's estimation errors are the motivation: a model trained on executed queries could correct the planner from experience instead of from a statistical model of the data. The main steps, dated:

YearSystemIdeaReported result
2015Join Order Benchmark (Leis et al., PVLDB)113 hand-written queries over real IMDb data to expose estimation errorsThe benchmark that Neo, Bao, Balsa and QORL all evaluate on, in its original or an extended form
2019Neo (Marcus et al., VLDB 2019)A deep network builds whole plans, bootstrapped from PostgreSQL's planner and learning from each execution"similar performance to state-of-the-art commercial optimizers, and in some cases even surpass them"
2021Bao (Marcus et al., SIGMOD 2021)Keep the planner; learn which set of hints (switching off join or scan methods) to give it for each query, with Thompson samplingLearns "an order of magnitude faster than previous approaches" and improves tail latency
2022Balsa (Yang et al., SIGMOD 2022)Reinforcement learning without copying an expert: a simple simulator first, then safe learning on real executionsMatches expert optimizers on JOB after two hours of learning, up to 2.8 times faster workload runtime after a few more
2026QORL (Bansal, 2026-09-16)A 4-billion-parameter language model (a Qwen 3.8 4B distillation) writes pg_hint_plan hints, trained by distillation then reinforcement learning on 13,646 Cardinality Estimation Benchmark queries, tested on JOB's 113 (no shared join shapes)See below
QORL, corrected
The old page credited the model with "a 1.81x geometric mean speedup and a 44.7% latency reduction ... with zero regressions". The write-up's results table separates three ways of picking a plan. The model's own choice, per run: 1.40 times geometric-mean speedup over Postgres, with 119 wins and 7 regressions (more than 5% slower) over 339 runs (113 queries, three runs each). Best candidate within a run, picked by a single feedback timing (the fastest, if at least 1.05 times the default, else the default) and then scored on separate paired timings: 1.44 times, 1 regression. The same rule across all three runs (up to 15 candidate plans per query, each executed): 1.81 times, 0 regressions over the 113 queries; "81% faster" and "44.7% lower latency" are that one measurement (summed medians 31.756 s against 57.398 s). The model's own choice is itself noisy: three repeated searches with the same weights gave 1.33 to 1.47 times, wider than most checkpoint-to-checkpoint differences in the write-up. Untrained, the model produced no usable plan for 99 of the 113. Cost: about $1,200 ($800 of GPU rental, $400 of API fees). The 1.81 needs measured feedback on each candidate, which only makes sense for a heavy query that runs again and again; and JOB served as the validation set during development, so it is not a pristine held-out test. The baseline is Postgres at its default random_page_cost of 4.0 on data held in memory, while one of the model's favourite hints set it to 1.1, the change section 9 suggests for cached data; how much of the gain one configuration line would give was not measured (our article page). Note the method too: queries were warmed until page hits and reads were stable within 2% before timing, the cold-against-warm trap of the parent's case 8.

In production today: none of these ships in PostgreSQL, and the practical lesson from Bao and QORL is that steering an existing planner with hints is far easier to deploy than replacing it. For an application team the takeaway is the reverse direction: everything a learned optimizer learns is a correction to row estimates, and sections 3 and 8 are how a person makes the same corrections today.