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.
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%'.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).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.
ANALYZE stores per column from a sample: null fraction, distinct count, most common values (MCV list), histogram, correlation.CREATE STATISTICS.work_mem and writes temporary files.| Section | The idea | Measured here |
|---|---|---|
| 1 | A query goes through parse, rewrite, plan, execute. The plan is a tree of steps. | |
| 2 | The 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 |
| 3 | Prices depend on row counts, which come from statistics that ANALYZE computes from a sample. | Distinct users in chats: estimated 75,971, really 99,945 |
| 4 | Estimates break on correlated columns, joins, functions and unknown parameters. | London users: estimated 165, really 2,294 |
| 5 | Nested 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 |
| 6 | Read EXPLAIN (ANALYZE, BUFFERS) bottom up; compare estimated with actual rows; count pages. | Per-node timing added 67% to one scan |
| 7 | Find (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 |
| 8 | Fixes, 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 |
| 9 | A 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 |
| 10 | Prepared 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 |
| 11 | Plans 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.
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.
messages, which type is chat_id.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.
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).
| Setting | Default | What it prices |
|---|---|---|
seq_page_cost | 1.0 | One page read as part of a sequential run |
random_page_cost | 4.0 | One page read by jumping to it (an index lookup) |
cpu_tuple_cost | 0.01 | Handling one row |
cpu_index_tuple_cost | 0.005 | Handling one index entry |
cpu_operator_cost | 0.0025 | Evaluating one operator, such as = or <=, once |
parallel_setup_cost, parallel_tuple_cost | 1000, 0.1 | Starting parallel workers; passing one row from a worker to the leader |
effective_cache_size | 4 GB | Not a cost: how much of the data the planner may assume is cached, used when pricing repeated index reads |
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:
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 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).
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.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 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:
| Query | Path | Planner cost | Pages touched | Time |
|---|---|---|---|---|
20,000 users by id (correlation -0.03) | Seq Scan | 2,780 | 1,280 | 5.4 ms |
| Index Scan | 5,733 | 19,460 | 3.4 ms | |
| Bitmap Heap Scan (chosen) | 2,003 | 375 | 2.4 ms | |
1,000,000 messages by id (correlation 1.00) | Seq Scan | 342,345 | 192,356 | 659 ms |
| Index Scan (chosen) | 51,384 | 25,294 | 137 ms | |
| Bitmap Heap Scan | 341,127 | 21,977 | 139 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.
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).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.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.
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_stats | Meaning | A real value from this database |
|---|---|---|
null_frac | Share of rows that are NULL | 0 for every column here |
n_distinct | Number 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_freqs | The most common values (MCV list), up to the target's count, with the share of rows each has | users.plan: free 0.8495, pro 0.1410, team 0.0095 (true: 0.8482, 0.1415, 0.0103) |
histogram_bounds | Boundaries that split the remaining values into buckets holding equal numbers of rows | messages.tokens: 101 bounds after 100 common values |
correlation | How closely physical row order follows the column's order (section 2) | messages.created_at: 1.00; chats.user_id: -0.003 |
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).
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).
| Target | Rows sampled | ANALYZE time | n_distinct stored | MCVs kept | Estimate, 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.
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:
1,000 rows, user 7 owns 1% of them. ANALYZE. Estimate for WHERE user_id = 7: 10, truth 10.
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.
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.
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.
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.
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.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.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.
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.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).
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.
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.
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.
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).
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).
-> 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 chatscost=0.42..37801.43rows=100width=19actual time=11.819..91.565rows=1 loops=1Filter, Rows Removed by FilterIndex Cond instead would mean the index did the filtering.Buffers: shared hit=12053This 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.
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.
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).
| Node | What it does | Worth noticing |
|---|---|---|
| Seq Scan / Parallel Seq Scan | Reads every page of a table | Fine 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 row | Delivers rows sorted by the index, which can make a Sort unnecessary |
| Index Only Scan | Answers from the index alone | Heap 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 Scan | Collects matching row locations, then reads pages in physical order | Heap Blocks: exact=, lossy=: lossy pages (when the bitmap outgrows work_mem) must recheck every row; Recheck Cond |
| Nested Loop | For each outer row, runs the inner side | Inner loops= is the number of outer rows; great when that is small, terrible when an underestimate made it large |
| Hash Join + Hash | Builds a hash table from one input, streams the other past it | Batches above 1 means the hash table spilled to disk |
| Merge Join | Zips two inputs sorted on the join key | Often fed by Sort nodes or index scans |
| Memoize | Caches inner results of a nested loop by key (PostgreSQL 14+) | Hits and Misses show whether the cache helped |
| Sort, Incremental Sort | Orders rows; incremental sort finishes an order that is already partly there | Sort Method: quicksort Memory (fine), top-N heapsort (a Limit above), external merge Disk (spilled) |
| HashAggregate, GroupAggregate, Aggregate | GROUP BY with a hash table, over sorted input, or one group for the whole input | HashAggregate Batches above 1 means it spilled |
| Gather, Gather Merge | Collects rows from parallel workers | Rows and times below it are per process: multiply by loops |
| Limit | Stops after n rows | Makes startup cost matter; a plan chosen "because it can stop early" is fragile when matches are rarer than estimated |
| Materialize, CTE Scan, SubPlan | Stores an intermediate result; a SubPlan runs once per outer row | A SubPlan with large loops is a correlated subquery that a join might replace |
| Append, Result, ProjectSet | Concatenates inputs (UNION ALL, partitions); computes expressions | Append over partitions shows which ones were pruned |
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.
"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.
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.
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.
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.
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?
total_exec_time: one statement, the title search, used 78.6% of all database time.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.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.title, 7 pages instead of 12,053: 0.078 ms for the same search.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.
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).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.
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.
The SQL asks for something the planner cannot do cheaply, or hides information from it. The rewrites that come up again and again:
created_at >= '2026-03-01' AND created_at < '2026-03-02', not created_at::date = '2026-03-01' (case 3).ORDER BY x LIMIT n with a rare filter on another column (section 7).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).Test that a rewrite returns the same rows.
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.
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).
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.
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.
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.
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).
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.
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.
| Setting | Default | What it does | Common practice |
|---|---|---|---|
shared_buffers | 128 MB | Postgres'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_size | 4 GB | Allocates nothing: tells the planner how much of the data is likely cached, which makes repeated index reads look cheaper | Roughly shared_buffers plus the operating system cache you expect Postgres to get, often half to three quarters of RAM |
work_mem | 4 MB | Memory for each sort or hash operation before it spills to temporary files; hashes may use hash_mem_multiplier (2.0) times more | Raise per role or per session for reports; keep the server default modest (below) |
random_page_cost | 4.0 | Price of a random page read (section 2) | Lowered on fast or fully cached storage, after measuring (below) |
max_parallel_workers_per_gather | 2 | Workers one parallel step may use | Raised for analytics, kept low for many small concurrent queries |
jit | on | Compiles expressions to machine code for expensive queries | Often left on for analytics, switched off for short transactional queries (below) |
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.
work_mem, JIT on or off), one setting at a time with before and after numbers from your own workload.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.
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).
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".
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.
SET 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.prepare=False on that call, or prepare_threshold=None on the connection.EXPLAIN (GENERIC_PLAN) (PostgreSQL 16+) shows the generic plan; pg_prepared_statements counts generic and custom plans per statement.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) */:
/*+ 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).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.
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
pg_stat_statements_reset().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).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:
| Year | System | Idea | Reported result |
|---|---|---|---|
| 2015 | Join Order Benchmark (Leis et al., PVLDB) | 113 hand-written queries over real IMDb data to expose estimation errors | The benchmark that Neo, Bao, Balsa and QORL all evaluate on, in its original or an extended form |
| 2019 | Neo (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" |
| 2021 | Bao (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 sampling | Learns "an order of magnitude faster than previous approaches" and improves tail latency |
| 2022 | Balsa (Yang et al., SIGMOD 2022) | Reinforcement learning without copying an expert: a simple simulator first, then safe learning on real executions | Matches expert optimizers on JOB after two hours of learning, up to 2.8 times faster workload runtime after a few more |
| 2026 | QORL (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 |
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.
Every plan here is real output of EXPLAIN (ANALYZE, BUFFERS) from the chat database used on this page (PostgreSQL 16.2, measured 2026-10-04). Each exercise asks you to find something by clicking a line of the plan, then to choose a fix. Wrong clicks are fine: the feedback says what that line means. The skills are those of Reading, section 6: read bottom up, compare estimated rows with actual rows times loops, count pages, look for spills and wasted rows.
Eight real EXPLAIN (ANALYZE, BUFFERS) outputs to diagnose, with answers. About 20 minutes.
The from-zero overview this page belongs to: one chat product's data from a file to a fleet. Its Query plans tab has the eight measured cases this page builds on (sequential against index scan, composite index order, sargability, join algorithms, a misestimate fixed by extended statistics, Postgres against DuckDB, index-only scans and VACUUM, cold against warm cache); the SQL playground runs SQL in your browser; the Database atlas compares about 50 systems. About 27 minutes plus the tabs.
Pages, B-trees, LSM-trees, the write-ahead log and every index type: the structures the planner chooses between. Child page, about 42 minutes.
Queries, joins, schema design and migrations: writing the SQL this page tunes. Child page, about 48 minutes.
MVCC and locks: why a query can be slow because it waits, not because it works. Child page, about 43 minutes.
Vacuum and autovacuum, connection pooling, upgrades, backups: the operations around the settings in section 9. Child page, about 43 minutes.
When the fix is a different engine: column stores for scans over millions of rows. Child page, about 46 minutes.
Substring and full-text search (the LIKE '%word%' case), and vector indexes with their own query planning problems. Child page, about 33 minutes.
When the cheapest query is the one you do not send. Child page, about 43 minutes.
Read replicas, sharding and distributed SQL: what to do after the queries are right and one server is still not enough. Child page, about 45 minutes.
Redis, DynamoDB, MongoDB, Cassandra, time series and graph databases, measured against Postgres. Child page, about 46 minutes.
Where the pagination measurement of section 8 was recorded, and the handler and API design around the queries (N+1 inside a request handler). Long read.
Tracing that shows how many queries each request makes: how N+1 patterns get noticed. Long read.
Queueing, load testing and why waiting dominates latency: the system-level side of section 7. Long read.
Its Numbers to know tab has the round-trip and disk latencies behind the N+1 arithmetic. About 21 minutes plus tabs.
Distillation and reinforcement learning, the training recipe behind QORL (the learned-optimizers block at the end of Reading). Long read.
PostgreSQL documentation, chapter 14: the clearest primary source on plans, costs, row estimates and extended statistics, with worked examples. About 1 hour.
Markus Winand's free book on indexing and SQL performance across databases: composite order, sargability, pagination, ORMs. About 4 hours.
Hironobu Suzuki's walk through parser, planner and executor, with the cost formulas worked by hand. About 1.5 hours.
Andy Pavlo's database systems course, lecture 15 (Fall 2024): slides, notes and video on how optimizers search and estimate. About 1.5 hours.
Leis et al., PVLDB 2015: the Join Order Benchmark, and the evidence that cardinality estimates, not cost models, decide plan quality. About 1 hour.
The two extensions behind section 7: every column and setting. About 30 minutes.
Paste a plan to see it as a tree with the expensive nodes highlighted; a reference for every field EXPLAIN prints. About 15 minutes to learn.
The learned optimizers of the closed block at the end of Reading. Read Bao first: it steers the existing planner, the approach that has proved practical. About 45 minutes each.
Rohan Bansal, 2026-09-16: QORL, with a careful measurement harness worth copying (warm-up until page counts settle). Read its results table, not its title; our article page recomputes it. About 1 hour.
Measurements: PostgreSQL 16.2 (pgserver wheel binaries, with pg_stat_statements, auto_explain and pageinspect built from the 16.2 source and pg_hint_plan REL16_1_6_1), DuckDB not used on this page, psycopg 3.3.6, on an Apple M1 Pro (16 GB), 2026-10-04. The data is the parent page's generator (100,000 users, 1,000,000 chats, 10,000,000 messages) plus one table of 4,000,000 billing events. Scripts and raw outputs: src/lab/ and src/inputs/ in the repository.