Query Planning, EXPLAIN & Join Algorithms
"The thing that's usually most important to look for is whether the estimated row counts are reasonably close to reality." — PostgreSQL documentation, 14.1. Using EXPLAIN
Summary: The planner turns declarative SQL into a tree of physical operators by estimating row counts from statistics and ranking candidate plans by cost; almost every slow query is a wrong estimate, not a missing feature. Focus: The parse → rewrite → plan → execute pipeline, cost constants, pg_stats and extended statistics, scan and join algorithms, sorts, aggregates, parallel query and JIT, reading EXPLAIN (ANALYZE, BUFFERS), generic vs custom plans, hints, and the MySQL and SQL Server equivalents. Learning goal: Read any plan, find the first node whose estimate is wrong, name the statistic or predicate behind it, and fix it with SQL, Go or Laravel before reaching for a hint.
This page is the complete reference for how a relational database chooses how to run a query and how you read and correct that choice. It covers the PostgreSQL planner in depth (it exposes the most), and positions MySQL/InnoDB, SQL Server, Oracle, SQLite, MongoDB and CockroachDB against it. Neighbours hold what this page only points at: which indexes exist and how to design them is Indexing; why a random page read costs more than a sequential one is B-Tree vs B+Tree and Database Internals; visibility maps and Heap Fetches come from MVCC, VACUUM & Bloat; partition pruning is taught in Partitioning & Sharding; fast LIMIT/OFFSET alternatives are Pagination; and wiring slow-query logs into dashboards is Database Observability.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why a planner exists and what it trades | Why the planner exists |
| System R, Selinger 1979, the Volcano model | Where it comes from |
| Each concept with plain words, a timeline, engines and a fix | The concepts, one by one |
| How to read a plan node by node, every EXPLAIN option and field | Reading EXPLAIN |
| MySQL, SQL Server, Oracle, SQLite, MongoDB, CockroachDB | Per-engine behaviour |
| Every knob with its default, memory, error codes, auto_explain, pg_stat_statements | Mechanics |
| Stale stats, correlated columns, nested-loop disasters, spills, generic plans | Solving the classic problems |
| Which tool for which situation | Choosing a fix |
| Monolith to distributed system | In architecture |
| Reproduce every effect yourself | Lab |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The pipeline. Unpacked in the pipeline block.
| Stage | What happens | What you can see |
|---|---|---|
| Parse | Grammar check, raw parse tree | Syntax errors (42601) |
| Analyze + rewrite | Names and types resolved, views and rules expanded | Unknown column/table errors (42703, 42P01) |
| Plan (optimize) | Candidate paths costed from statistics, cheapest becomes the plan tree | EXPLAIN |
| Execute | Iterator tree pulls rows node by node (Volcano model) | EXPLAIN ANALYZE, auto_explain, pg_stat_statements |
The operators.
| Operator | In plain words | Good when | Bad when |
|---|---|---|---|
| Seq Scan | Read every page in order | Large fraction of rows, tiny tables | Few rows wanted from a big table |
| Index Scan | Walk index, jump to heap per row | Few rows, or index order serves ORDER BY | Many rows: random I/O per row |
| Index Only Scan | Answer from the index alone | Covered columns, pages all-visible | Visibility map stale: Heap Fetches high |
| Bitmap Heap Scan | Collect row locations, read heap in physical order | Middle ground; combine indexes with BitmapAnd/BitmapOr | Bitmap goes lossy under low work_mem |
| Nested Loop | For each outer row, probe the inner side | Small outer side, indexed inner, LIMIT | Outer estimate far too low |
| Hash Join | Build hash table from one side, probe with the other | Large unsorted equality joins | Build side does not fit: Batches > 1 |
| Merge Join | Walk two sorted inputs together | Both sides already ordered | Explicit sorts that spill |
| Sort / Incremental Sort / top-N heapsort | Full sort / sort by groups of a presorted prefix / keep only N best | ORDER BY, DISTINCT, merge join input | external merge Disk: |
| HashAggregate / GroupAggregate | Group in a hash table / group sorted input | Few groups / input already sorted | Many groups under low memory |
| Gather / Gather Merge | Collect rows from parallel workers | Big scans and aggregates | Tiny queries, many groups |
The five things to do.
| Situation | Do this |
|---|---|
| A query is slow | EXPLAIN (ANALYZE, BUFFERS); find the lowest node where estimated and actual rows differ by 10× or more |
| Estimates wrong after a load | ANALYZE table as the last step of every bulk load or backfill |
| Two filtered columns move together | CREATE STATISTICS ... (dependencies, mcv) ON a, b FROM t; ANALYZE t; |
| Sort or hash spills | Raise work_mem for that transaction with SET LOCAL, not globally |
| Fast in psql, slow from the app | Suspect a generic plan; compare EXPLAIN EXECUTE, try plan_cache_mode = force_custom_plan |
Why the planner exists
SQL says what rows you want, never how to fetch them. For a three-table join with two usable indexes per table there are already dozens of correct ways to run it, and their run times differ by factors of a thousand. Somebody must choose, every time, in milliseconds, without running the alternatives. That chooser is the planner (PostgreSQL's term) or optimizer (MySQL, SQL Server, Oracle). It predicts how many rows each step will produce, turns those row counts into a cost, and keeps the cheapest plan. Everything that goes wrong in practice is a wrong prediction: the arithmetic is fine, the inputs are not.
| Planning less (cheap, rule-based, cached) | Planning more (cost-based, per execution) |
|---|---|
| Fast to plan, predictable | Better plan for each value and data shape |
| Ignores data distribution | Depends on fresh, representative statistics |
| One plan for all parameter values (generic) | Plan per parameter value (custom); costs planning time each call |
| Stable across data changes | Can flip to a different plan after ANALYZE or growth |
| SQLite's nested-loop-only executor, MongoDB's cached winning plan | PostgreSQL, SQL Server, Oracle, MySQL 8 cost-based optimizers |
The analogy we reuse on this page: a delivery dispatcher. Every evening a dispatcher plans tomorrow's routes from last month's traffic map. For each neighbourhood the choice is knocking on every door in order (sequential scan), driving to specific addresses from a list (index scan), or sorting the list by street first and then driving it (bitmap scan). For joining two lists of parcels, the dispatcher can match each parcel against the other list one by one (nested loop), put one list into labelled pigeon-holes and drop the other in (hash join), or sort both by postcode and walk them together (merge join). The plan is only as good as the map. If a new housing estate opened last week, the dispatcher still plans for an empty field and sends one van. The fix is not a faster van; it is updating the map (ANALYZE).
Three common misunderstandings, up front
- "Cost is milliseconds." Cost is in units of one sequential page fetch (
seq_page_cost = 1.0). It ranks plans for one query; it does not predict time. - "A Seq Scan means a missing index." For a large fraction of rows a sequential scan is the cheapest plan. The question is whether the row estimate that led to it was right.
- "Hints are how you tune queries." Hints freeze a plan that was right for yesterday's data. Fix the estimate (statistics, predicate shape, schema) first; pin a plan last.
Where it comes from
The template every relational planner still follows comes from IBM's System R, described by Patricia Selinger and colleagues at SIGMOD 1979 in "Access Path Selection in a Relational Database Management System". The optimizer gave each candidate plan a number:
"COST = PAGE FETCHES + W * (RSI CALLS)."
The paper explains: "This cost is a weighted measure of I/O (pages fetched) and CPU utilization (instructions executed)." Three ideas from that paper are still in every modern planner. Each predicate gets a selectivity factor from catalog statistics (System R fell back to a flat 1/10 for column = value when it had nothing better). Sorted output has value: "We say that a tuple order is an interesting order if that order is one specified by the query block's GROUP BY or ORDER BY clauses", and every join column defines one too. And the join order is found by building the best plan for successively larger subsets of tables, which is dynamic programming. System R had two join methods, nested loops and "merging scans"; hash joins came later.
The authors were candid about accuracy: "although the costs predicted by the optimizer are often not accurate in absolute value, the true optimal path is selected in a large majority of cases." That sentence is still the right mental model: costs are for ranking plans, not for predicting milliseconds.
PostgreSQL names the lineage in its GEQO chapter: its normal search is near-exhaustive, and "This algorithm, first introduced in IBM's System R database, produces a near-optimal join order, but can take an enormous amount of time and memory space when the number of joins in the query grows large."
The execution side follows the Volcano (or iterator) model, associated with Goetz Graefe's Volcano work in the early 1990s (named here from secondary knowledge, not quoted): every operator exposes open(), next(), close(), and a parent pulls one row at a time from its children. PostgreSQL's executor, MySQL's iterator executor (the one EXPLAIN ANALYZE reports on) and SQL Server's operators all follow this pull model, which is why a plan is a tree and why Limit can stop its children early.
The concepts, one by one
The pipeline: parse, rewrite, plan, execute Must-know
In plain words: the database first checks your SQL is grammatical, then works out what every name means and expands views, then picks a plan, then runs it. Only the third step is "the planner".
Common misunderstanding: "EXPLAIN shows how long my query took to plan and parse." The Planning Time line excludes parsing and rewriting, and a plain EXPLAIN does not execute anything.
Definition: PostgreSQL's Path of a Query lists the stages: the parser builds a parse tree; the rewrite system applies rules (views are rules); the planner/optimizer, whose task (in the Planner/Optimizer chapter's words) "is to create an optimal execution plan", works by building paths (cut-down plans), costing each, keeping the cheapest and expanding it into a full plan tree; the executor walks the tree recursively, pulling rows (the iterator model).
client backend
1 SELECT ... FROM v_orders ... parse -> raw parse tree
2 analyze -> query tree, names/types resolved
3 rewrite -> view v_orders replaced by its SELECT
4 plan -> paths costed; cheapest -> plan tree
5 execute -> root.next() -> child.next() -> ... rows
6 <- rows (prepared statement: steps 1-3 once, step 4 cached or redone)Real scenarios: a view stacked on three other views plans like one big query, because rewrite flattens them; a prepared statement skips parse/analysis on every call, which is why ORMs and pgx prepare; a SELECT with a syntax error never reaches the planner, so auto_explain never logs it.
| Engine | Pipeline names | Plan cache |
|---|---|---|
| PostgreSQL | parser, rewriter, planner, executor | Per session, for prepared statements |
| MySQL 8 | parser, resolver, optimizer, iterator executor | No shared plan cache; prepared statements re-optimise |
| SQL Server | parse, bind (algebrizer), optimize, execute | Instance-wide plan cache, keyed by query text |
| Oracle | parse (hard/soft), optimize, row source generation, execute | Shared pool (library cache) |
| SQLite | tokenizer/parser, code generator, VDBE bytecode | Per prepared sqlite3_stmt |
Fix / how to use it: in SQL, EXPLAIN stops after step 4's planning; EXPLAIN ANALYZE also executes. In Go, prepare hot statements once (db.PrepareContext) so parse/analysis is paid once. In Laravel, the query builder uses PDO prepared statements; toSql() shows the text the parser will see.
Cost model and the cost constants Must-know
In plain words: the planner prices each plan in "page reads", adding CPU work as fractions of a page read, and picks the cheapest.
Common misunderstanding: "Lowering random_page_cost makes queries faster." It changes which plan looks cheaper (index scans start winning). On SSDs with a warm cache that is often right; on a cold spinning disk it is a lie the planner will believe.
Definition: costs are "arbitrary units" anchored on seq_page_cost = 1.0. The manual gives the sequential scan formula: "The estimated cost is computed as (disk pages read * seq_page_cost) + (rows scanned * cpu_tuple_cost)." Its tenk1 table has 345 pages and 10,000 rows, so 345 × 1.0 + 10,000 × 0.01 = 445, exactly what EXPLAIN prints. Each node shows cost=startup..total: start-up is the cost before the first row (a Sort must consume everything first; a Seq Scan starts at 0), total includes all children. rows is the estimated output rows and width the average row width in bytes.
EXPLAIN SELECT * FROM tenk1 WHERE unique1 < 7000;
1 pg_class: relpages = 345, reltuples = 10000
2 pages: 345 * seq_page_cost (1.0) = 345
3 tuples: 10000 * cpu_tuple_cost (0.01) = 100
4 filter: 10000 * cpu_operator_cost (0.0025) = 25
5 total: 470 -> Seq Scan ... cost=0.00..470.00 rows=7000| Constant | Default (PostgreSQL 19) | Meaning |
|---|---|---|
seq_page_cost | 1.0 | One page read in sequence |
random_page_cost | 4.0 | One non-sequential page read; 1.1–2.0 is common on SSD |
cpu_tuple_cost | 0.01 | Processing one row |
cpu_index_tuple_cost | 0.005 | Processing one index entry |
cpu_operator_cost | 0.0025 | Evaluating one operator or function call |
parallel_setup_cost | 1000 | Starting parallel workers |
parallel_tuple_cost | 0.1 | Passing one row from worker to leader |
effective_cache_size | 4GB | Planner's belief about OS + shared cache; allocates nothing |
Real scenarios: a cloud database on SSD with random_page_cost = 4 choosing seq scans for 2% selectivity; a 16 GB server with effective_cache_size left at 4GB, under-valuing index scans; a tablespace on slow storage given its own seq_page_cost via ALTER TABLESPACE ... SET.
Fix / how to use it: set cost constants per tablespace or server from measurement, never per query to force a plan. Compare costs only between plans for the same query.
Statistics: ANALYZE and pg_stats Must-know
In plain words: before planning, the database looks at a summary of your data: how big each table is, how many distinct values a column has, which values are most common, and how the rest are spread out.
Common misunderstanding: "EXPLAIN ANALYZE refreshes statistics." It is EXPLAIN that executes; it updates nothing. The command that refreshes statistics is ANALYZE (or autovacuum's auto-analyze).
Definition: pg_class.reltuples and relpages give table size. pg_stats, a readable view over pg_statistic, gives per column: null_frac (fraction NULL), avg_width, n_distinct (positive: count; negative: fraction of rows, so -1 means unique), most_common_vals and most_common_freqs (the MCV list), histogram_bounds (equal-population buckets over the non-MCV values), and correlation (physical vs logical order, -1..1; near ±1 makes index range scans cheaper). ANALYZE builds these from a random sample of 300 × default_statistics_target rows. default_statistics_target (100) caps the MCV list and histogram size; per column use ALTER TABLE t ALTER COLUMN c SET STATISTICS 500.
time event planner sees
1 09:00 orders: 1M rows, ANALYZEd reltuples = 1,000,000
2 09:05 bulk load adds 9M rows for tenant 42 still 1,000,000; tenant 42 not in MCV
3 09:06 report: WHERE tenant_id = 42 estimate 30 rows -> Nested Loop + Index Scan
4 09:06 actual: 9,000,000 rows query runs 40 minutes
5 09:07 ANALYZE orders; tenant 42 in MCV with freq 0.9
6 09:07 same report estimate 9M -> Hash Join, Parallel Seq Scan, 40 sReal scenarios: a nightly ETL that loads and immediately reports; a multi-tenant table where one tenant owns 90% of rows; a status column where 'pending' is 0.1% and the planner must know it; a timestamp column whose histogram ends yesterday, so created_at > now() - interval '1 hour' estimates one row (the "out of histogram range" problem).
| Engine | Statistics object | Refresh |
|---|---|---|
| PostgreSQL | pg_statistic / pg_stats, pg_statistic_ext | ANALYZE, autovacuum (autovacuum_analyze_scale_factor 0.1) |
| MySQL InnoDB | Persistent index stats (innodb_stats_persistent), histograms in data dictionary | ANALYZE TABLE, auto-recalc on ~10% change; histograms only by ANALYZE TABLE ... UPDATE HISTOGRAM |
| SQL Server | Statistics objects with histogram (≤ 200 steps) + density | AUTO_UPDATE_STATISTICS, UPDATE STATISTICS |
| Oracle | DBMS_STATS, histograms (frequency, height-balanced, hybrid) | Automatic stats job, DBMS_STATS.GATHER_TABLE_STATS |
| SQLite | sqlite_stat1, sqlite_stat4 | ANALYZE, PRAGMA optimize |
| MongoDB | No column histograms; plan chosen by trial execution | Plan cache flushed on index or data changes |
Fix: SQL ANALYZE orders; after loads; Go and Laravel below in stale statistics.
SELECT attname, null_frac, n_distinct, most_common_vals, most_common_freqs,
histogram_bounds, correlation
FROM pg_stats
WHERE schemaname = 'public' AND tablename = 'orders' AND attname IN ('tenant_id', 'status');Extended statistics: CREATE STATISTICS Must-know
In plain words: you tell the database "these two columns move together, measure them as a pair", so it stops assuming they are unrelated.
Common misunderstanding: "CREATE STATISTICS fixes the plan immediately." It only registers interest; the next ANALYZE collects the data.
Definition: "The planner normally assumes that multiple conditions are independent of each other, an assumption that does not hold when column values are correlated." CREATE STATISTICS name (kinds) ON col1, col2 FROM t collects, per chosen kind: ndistinct (distinct count of column combinations, for GROUP BY a, b), dependencies (functional dependency degree, for a = x AND b = y), and mcv (most-common value combinations with frequencies, the most powerful for equality and some range clauses). It can also target an expression, CREATE STATISTICS s ON (lower(email)) FROM customers, giving a function its own distribution without building an index. Results are visible in pg_stats_ext and pg_stats_ext_exprs.
WHERE city = 'Berlin' AND zip = '10115' (zip determines city)
1 sel(city = 'Berlin') = 0.05
2 sel(zip = '10115') = 0.001
3 independent: 0.05 * 0.001 = 0.00005 -> 1M rows * 0.00005 = 50 rows estimated
4 reality: every 10115 row is Berlin -> 1,000 rows actual (20x under)
5 CREATE STATISTICS addr_stx (dependencies, mcv) ON city, zip FROM addresses; ANALYZE addresses;
6 estimate ~1,000 rows -> Hash Join instead of Nested LoopReal scenarios: country and vat_zone; status and channel on orders; make and model on cars; tenant_id and user_id where users belong to one tenant; GROUP BY city, zip overestimating groups and choosing a sort-based aggregate.
| Engine | Multi-column statistics |
|---|---|
| PostgreSQL | CREATE STATISTICS with ndistinct, dependencies, mcv, expressions |
| MySQL | Index prefix cardinality only for indexed columns; histograms are single-column |
| SQL Server | Multi-column statistics objects (CREATE STATISTICS ON t(a, b)), density vector for the prefix |
| Oracle | Column groups via DBMS_STATS.CREATE_EXTENDED_STATS, expression statistics |
| CockroachDB | Multi-column statistics collected automatically on index prefixes |
Fix: SQL as above; the Go snippet in Solving the classic problems runs it after loads.
Selectivity estimation and its failure modes Must-know
In plain words: selectivity is the fraction of rows a condition keeps. The planner multiplies it by the table size to guess how many rows come out. When it has no data, it guesses a constant.
Common misunderstanding: "If the planner has statistics on a column, every condition on that column is estimated well." Wrap the column in a function, compare it to another column, or use LIKE '%x%', and the planner falls back to defaults.
Definition: equality uses the MCV list (exact frequency) or (1 - sum(mcv_freqs)) / (n_distinct - n_mcv) for other values; ranges interpolate inside histogram_bounds; AND multiplies, OR adds minus overlap; IN (a, b, c) sums the equality selectivities; joins estimate 1 / max(n_distinct(a), n_distinct(b)). Without statistics for an expression, "The equality and range conditions are assumed to have 0.5% selectivity". Dependency statistics are "not used to improve estimates for equality conditions comparing two columns or comparing a column to an expression, nor for range clauses, LIKE or any other type of condition."
| Failure mode | Typical predicate | Why the estimate is wrong | Fix |
|---|---|---|---|
| Correlated columns | city = $1 AND zip = $2 | Independence assumption | CREATE STATISTICS (dependencies, mcv) |
| Function on column | lower(email) = $1, date(created_at) = $1 | No distribution for the expression | Expression statistics or expression index |
LIKE / regex | name LIKE '%son%' | Leading wildcard: default guess | Trigram index (pg_trgm) for the scan; accept the estimate |
Long IN lists | id IN (... 5,000 values ...) | Summed per-value guesses; planning time | = ANY($1::bigint[]), or join to a VALUES list or temp table |
| Out-of-range values | created_at > now() - '1h' | Histogram ends at last ANALYZE | More frequent ANALYZE; PostgreSQL probes the index end for the actual max |
| Stale statistics | After a bulk load | reltuples and MCV describe old data | ANALYZE in the load job |
| Skewed join keys | One tenant with 90% of rows | Join estimate uses averages | MCV on join key; per-tenant plans; plan_cache_mode |
| Type mismatch | varchar_col = 123 | Cast on column defeats index and stats | Compare with correctly typed parameters |
estimate cascade (each level multiplies the error)
1 Seq Scan addresses est 12 actual 48,210 <- correlated columns (4,000x)
2 Nested Loop est 12 actual 48,210 <- chosen because of line 1
3 Index Scan customers loops=48,210 <- 48k random lookups
4 Sort est 12 rows -> work_mem fine; actual 48k -> spills to diskReal scenarios: search pages with ILIKE, reports filtering on date_trunc('day', created_at), an admin bulk tool posting 10,000 ids in an IN list, an ORM comparing a uuid column to text.
Scan types: seq, index, index-only, bitmap Must-know
In plain words: there are four ways to get rows out of a table: read it all, follow the index row by row, answer from the index alone, or collect addresses from the index and read the table in disk order.
Common misunderstanding: "An Index Only Scan never touches the table." It skips the heap only for pages the visibility map marks all-visible; Heap Fetches: N counts the rows it still had to check. After heavy updates and before VACUUM, it can be as slow as an Index Scan.
Definition: Seq Scan reads every page and filters (Filter: and Rows Removed by Filter:). Index Scan uses Index Cond: and fetches heap tuples in index order; it can return sorted output and stop early under Limit. Index Only Scan needs every referenced column in the index (or INCLUDE). Bitmap Index Scan builds a bitmap of TIDs; Bitmap Heap Scan reads pages in physical order and rechecks (Recheck Cond:); when the bitmap exceeds work_mem it becomes lossy (page-level), shown as Heap Blocks: exact=… lossy=…. BitmapAnd/BitmapOr combine indexes. Tid Scan fetches by ctid. Parallel variants exist for seq, index and bitmap heap scans.
fraction of rows matched -> typical PostgreSQL choice
1 < ~0.1% (a handful) Index Scan (or Index Only Scan if covered)
2 ~0.1% .. ~5-10% Bitmap Index Scan -> Bitmap Heap Scan
3 > ~10% Seq Scan (Parallel Seq Scan on big tables)
4 any, with ORDER BY + LIMIT Index Scan in index order, stopped by Limit
(boundaries move with correlation, random_page_cost, effective_cache_size)| Engine | Names in the plan |
|---|---|
| PostgreSQL | Seq Scan, Index Scan, Index Only Scan, Bitmap Index/Heap Scan, Tid Scan |
MySQL EXPLAIN type column | ALL (full scan), index (full index), range, ref, eq_ref, const; Using index = covering; Using index condition = ICP |
| SQL Server | Table Scan / Clustered Index Scan, Index Seek, Key Lookup (heap/clustered fetch) |
| Oracle | TABLE ACCESS FULL, INDEX RANGE SCAN, TABLE ACCESS BY INDEX ROWID, INDEX FAST FULL SCAN |
SQLite EXPLAIN QUERY PLAN | SCAN t, SEARCH t USING INDEX, USING COVERING INDEX |
MongoDB explain() | COLLSCAN, IXSCAN + FETCH, covered query when totalDocsExamined: 0 |
Fix / how to use it: index design is in Indexing; here the job is to check that the planner's choice matches the actual row count. If Rows Removed by Filter is huge on a seq scan that returns few rows, an index is missing or unusable (function, type mismatch). If an index scan returns 40% of the table, the estimate was wrong.
Join algorithms: nested loop, hash, merge Must-know
In plain words: nested loop checks each row of one side against the other; hash join builds a lookup table from one side and probes it; merge join walks two sorted lists together.
Common misunderstanding: "Nested loops are bad and hash joins are good." A nested loop over 10 outer rows with an index on the inner side is the fastest join there is and returns its first row immediately. It becomes a disaster only when the outer estimate is wrong.
Definition:
| Join | Mechanism | Cost shape | Memory | Picked when |
|---|---|---|---|---|
| Nested Loop | For each outer row, run the inner plan (ideally an index lookup on the join key); loops on the inner node = outer rows | outer rows × inner cost | None (optional Memoize cache, enable_memoize) | Small outer side; non-equality conditions (<, LIKE, BETWEEN); LIMIT |
| Hash Join | Hash child builds a table from the (estimated) smaller input; parent probes it with each outer row (Hash Cond:) | build + probe, roughly linear | work_mem × hash_mem_multiplier (4 MB × 2.0); beyond that, Batches > 1 and temp files | Equality joins of large unsorted inputs |
| Merge Join | Both inputs sorted on the key (index or Sort), merged in one pass (Merge Cond:) | sort + linear merge | Only for the sorts | Inputs already ordered; output order useful upstream; very large inputs |
Hash Join with work_mem = 4MB, build side 300 MB
1 planner: est build rows -> nbatch = 128 (Batches: 128 planned)
2 build: hash key mod 128 -> batch 0 kept in memory, batches 1..127 written to temp files
3 probe: outer rows for batch 0 probed now; others written to matching temp files
4 loop: for batch 1..127: load inner batch file, probe with outer batch file
5 EXPLAIN: Buckets: 131072 Batches: 128 Memory Usage: 4057kB
6 BUFFERS: temp read=73400 written=73400 <- the spill you pay for
(if the estimate was too low the executor doubles batches at run time: "Batches: 256 (originally 128)")Real scenarios: an order page joining 20 order lines to products (nested loop + index); a nightly report joining 50M events to 2M users (hash join, possibly parallel hash); a merge join between two tables both clustered by date for an export; a LATERAL subquery that forces a nested loop by design; Memoize caching a lookup when many outer rows repeat the same key.
| Engine | Nested loop | Hash join | Merge join |
|---|---|---|---|
| PostgreSQL | Yes, plus Memoize | Yes, plus Parallel Hash | Yes |
| MySQL 8 | Yes (Block Nested Loop replaced; Batched Key Access optional) | Since 8.0.18; memory join_buffer_size, spills to disk files | No |
| SQL Server | Nested Loops | Hash Match | Merge Join; plus Adaptive Join (switches at run time) |
| Oracle | NESTED LOOPS | HASH JOIN | SORT MERGE JOIN; adaptive plans |
| SQLite | Only nested loop (with automatic indexes) | No | No |
MongoDB $lookup | Per-document lookup (index on foreignField matters); slot-based engine can hash join | Yes in the slot-based engine (6.0+) | No |
Fix / how to use it: fix the outer estimate first. If you must test, SET LOCAL enable_nestloop = off inside a transaction shows what the alternative costs; it is an experiment, not a fix. For hash spills, see spills.
Join order search, collapse limits and GEQO Important
In plain words: with many tables the planner must also choose the order in which to join them, and the number of orders explodes. Past a limit it stops searching exhaustively.
Common misunderstanding: "The order I write my JOINs in does not matter." For up to join_collapse_limit (8) items it does not; beyond that, the written order is kept for the remainder, and with 12 or more FROM items GEQO searches randomly.
Definition: inner joins can be reordered freely. PostgreSQL uses dynamic programming over subsets (System R style). It flattens subqueries into the parent's FROM list while the result stays within from_collapse_limit (8), and explicit JOIN syntax into the list within join_collapse_limit (8; setting 1 forces the written order). At geqo_threshold (12) FROM items it switches to the Genetic Query Optimizer, which treats join order like a travelling-salesman problem and searches a random sample of orders; it is reproducible because it reseeds from geqo_seed each run. FULL JOIN is never reordered; outer joins are reordered only where the rules allow.
tables possible left-deep orders PostgreSQL behaviour
1 3 6 exhaustive DP
2 8 40,320 exhaustive DP (at collapse limit)
3 12 479,001,600 GEQO (geqo_threshold = 12)
4 20 2.4 * 10^18 GEQO; planning time and plan quality varyReal scenarios: a BI report with 14 joined dimension tables whose plan changes between runs; an ORM eager-load building one giant query; a view stack where flattening pushes the FROM list past 8.
| Engine | Search strategy and knob |
|---|---|
| PostgreSQL | DP to join_collapse_limit/from_collapse_limit, GEQO at geqo_threshold |
| MySQL | Greedy search bounded by optimizer_search_depth (default 62; 0 means automatic) and optimizer_prune_level; STRAIGHT_JOIN / JOIN_ORDER hint |
| SQL Server | Transformation-based search that can stop early (plan property "Reason For Early Termination Of Statement Optimization: Time Out") |
| Oracle | Cost-based permutation search with a cutoff; LEADING, ORDERED hints |
Fix: keep queries under the limit, or set join_collapse_limit per transaction and write the order you want; move very wide reports to a read model (OLTP vs OLAP).
Sort, Incremental Sort and top-N heapsort Important
In plain words: sorting everything is expensive; sorting only inside groups that are already in order is cheaper; keeping only the best N rows is cheapest.
Common misunderstanding: "ORDER BY ... LIMIT 10 sorts the whole table." With no usable index it still reads everything, but the sort keeps only 10 rows in a heap (Sort Method: top-N heapsort), so it never spills.
Definition: Sort consumes all input before returning the first row (high start-up cost). Sort Method: reports quicksort (in memory), top-N heapsort (bounded by LIMIT) or external merge Disk: NkB (spilled to temp files). Incremental Sort appears when input is ordered on a prefix of the keys (Presorted Key:); it sorts each group separately, which "allows returning tuples before the entire result set has been sorted" and helps LIMIT (enable_incremental_sort).
ORDER BY customer_id, created_at LIMIT 20 index on (customer_id)
1 Index Scan on customer_id -> rows arrive ordered by customer_id
2 Incremental Sort -> Presorted Key: customer_id; sort created_at within each customer
3 Limit -> stops after 20 rows; most groups never read| Engine | Sort spill signal |
|---|---|
| PostgreSQL | Sort Method: external merge Disk: 51200kB; temp written in BUFFERS |
| MySQL | Using filesort in Extra; sort_buffer_size; Sort_merge_passes status |
| SQL Server | Sort warning "Operator used tempdb to spill data" in the actual plan |
| Oracle | TEMP usage in V$SQL_WORKAREA (one-pass / multi-pass) |
Aggregates: HashAggregate vs GroupAggregate Good to know
In plain words: grouping is either a hash table keyed by the group (any order) or a walk over sorted input (one group at a time).
Common misunderstanding: "GROUP BY always sorts." HashAggregate does not; since PostgreSQL 13 it can also spill to disk instead of overrunning memory (Batches, Disk Usage lines).
Definition: HashAggregate uses work_mem × hash_mem_multiplier; GroupAggregate needs input sorted on the group keys (index or Sort); MixedAggregate serves GROUPING SETS; parallel plans split into Partial Aggregate in each worker and Finalize Aggregate in the leader. A badly overestimated number of groups pushes the planner to sort; underestimated groups make HashAggregate spill.
SELECT status, count(*) FROM orders GROUP BY status; (5 groups, 50M rows)
1 Parallel Seq Scan (3 processes)
2 Partial HashAggregate in each worker -> 5 rows each
3 Gather -> 15 rows
4 Finalize HashAggregate -> 5 rowsParallel query: workers and Gather Important
In plain words: a big scan or aggregate is split across several processes, and a Gather node collects their rows.
Common misunderstanding: "Workers Planned: 4 means four workers ran." Workers Launched can be lower when the pool of max_parallel_workers or max_worker_processes is busy, and the query then runs slower than planned.
Definition: "When the optimizer determines that parallel query is the fastest execution strategy for a particular query, it will create a query plan that includes a Gather or Gather Merge node." Only the subtree below Gather runs in parallel; "Gather reads tuples from the workers in whatever order is convenient", while Gather Merge preserves sort order. Workers are capped by max_parallel_workers_per_gather (2), max_parallel_workers (8) and max_worker_processes (8); tables smaller than min_parallel_table_scan_size (8MB) do not qualify. In a parallel hash join, the inner side "is a parallel hash that divides the work of building a shared hash table over the cooperating processes" (Parallel Hash, enable_parallel_hash). Partitioned tables can use Parallel Append. Per-loop numbers are averaged over the leader and workers, which is why actual rows print as decimals.
leader worker 1 worker 2
1 Gather: request 2 workers start start
2 scan own share of blocks Parallel Seq Scan Parallel Seq Scan
3 read tuples from queue <- send tuples <- send tuples
4 Finalize / return rows exit exit
EXPLAIN: Workers Planned: 2 Workers Launched: 2 (loops=3 on parallel nodes)| Engine | Intra-query parallelism |
|---|---|
| PostgreSQL | Gather / Gather Merge, parallel seq/index/bitmap scans, parallel hash, partial aggregates |
| MySQL | Parallel clustered-index reads for SELECT COUNT(*) and CHECK TABLE (innodb_parallel_read_threads); general queries single-threaded |
| SQL Server | MAXDOP, cost threshold for parallelism, Parallelism (Gather Streams / Repartition Streams) operators |
| Oracle | Parallel execution with PX servers, PARALLEL hint |
| CockroachDB | Distributed SQL: plan fragments run on the nodes holding the ranges |
JIT compilation Good to know
In plain words: for a very expensive query, PostgreSQL can compile its expressions to machine code with LLVM before running them.
Common misunderstanding: "JIT makes every query faster." Compilation costs tens to hundreds of milliseconds; on short OLTP queries whose estimated cost is inflated by a bad estimate, JIT can be most of the run time.
Definition: "Currently PostgreSQL's JIT implementation has support for accelerating expression evaluation and tuple deforming." It is used when the total estimated cost exceeds jit_above_cost (100000); above jit_inline_above_cost (500000) small functions are inlined, and above jit_optimize_above_cost (500000) expensive LLVM optimizations run. The PostgreSQL 19 manual lists jit as default off; earlier releases from 12 shipped with it on, so check your version. EXPLAIN ANALYZE prints a JIT: block with Functions, Options and Timing: Generation, Inlining, Optimization, Emission.
OLTP query, bad estimate -> cost 600,000 (actual 200 rows)
1 planner: cost > jit_above_cost, > inline, > optimize -> JIT on, all stages
2 JIT: Timing: Generation 4 ms, Inlining 60 ms, Optimization 120 ms, Emission 70 ms
3 Execution Time: 260 ms (query itself: 6 ms)
4 fix the estimate, or SET jit = off for the OLTP roleGeneric vs custom plans and parameter sniffing Must-know
In plain words: a prepared statement can be planned for the exact values you pass (custom) or once for any value (generic). A generic plan that suits most values can be terrible for a rare one.
Common misunderstanding: "My query is fast in psql and slow in the app, so the app or network is slow." psql sends literal values (custom plan every time); the app sends $1 through a prepared statement and, after five executions, may be on a generic plan.
Definition: plan_cache_mode doc: "Custom plans are made afresh for each execution using its specific set of parameter values, while generic plans do not rely on the parameter values and can be re-used across executions." The PREPARE rule: "the first five executions are done with custom plans and the average estimated cost of those plans is calculated", after which a generic plan is used if its cost is not much more expensive. Values: auto (default), force_custom_plan, force_generic_plan. EXPLAIN EXECUTE stmt(…) shows $1 in conditions when the generic plan is in use; EXPLAIN (GENERIC_PLAN) SELECT … $1 shows the generic plan without preparing. The term parameter sniffing comes from SQL Server, where "the Database Engine sniffs the current parameter values during compilation or recompilation"; PostgreSQL's manual does not use it.
PREPARE q(int) AS SELECT * FROM orders WHERE tenant_id = $1; tenant 42 = 90% of rows
1 EXECUTE q(7) custom plan: Index Scan (est 40 rows)
2 EXECUTE q(8) custom plan: Index Scan
3 EXECUTE q(9) .. q(11) custom plans; average custom cost recorded
4 EXECUTE q(12) generic plan chosen: Index Scan, est 1/n_distinct rows
5 EXECUTE q(42) generic Index Scan over 9M rows <- the incident
6 SET plan_cache_mode = force_custom_plan; EXECUTE q(42) -> Parallel Seq Scan + Hash| Engine | Parameterised plan behaviour | Escape hatch |
|---|---|---|
| PostgreSQL | 5 custom plans, then generic if not much costlier | plan_cache_mode, per role/database/transaction |
| SQL Server | Plan compiled with sniffed values, cached and reused | OPTION (RECOMPILE), OPTIMIZE FOR, Parameter Sensitive Plan optimization (compatibility level 160) |
| Oracle | Bind variable peeking; adaptive cursor sharing creates bind-sensitive child cursors | /*+ BIND_AWARE */, SQL plan baselines |
| MySQL | Prepared statements are re-optimised on each execution; no shared plan cache | n/a |
| MongoDB | Plan cache per query shape; entries replanned when performance degrades | planCacheClear |
Fix: SQL, Go and Laravel in Generic plan regression.
CTEs, subquery unnesting and predicate pushdown Important
In plain words: the planner rewrites your query: it pulls subqueries up into joins, pushes filters down to the scans, and inlines CTEs, unless you or the semantics stop it.
Common misunderstanding: "A CTE is always an optimisation fence in PostgreSQL." That was true before PostgreSQL 12. Since then a non-recursive, side-effect-free CTE referenced once is folded into the parent query.
Definition: "if a WITH query is non-recursive and side-effect-free (that is, it is a SELECT containing no volatile functions) then it can be folded into the parent query, allowing joint optimization of the two query levels. By default, this happens if the parent query references the WITH query just once". WITH x AS MATERIALIZED (…) forces separate evaluation (a fence: filters from outside are not pushed in); NOT MATERIALIZED forces folding even when referenced twice. Subquery unnesting: IN (SELECT …) and EXISTS (…) become semi-joins, NOT EXISTS becomes an anti-join (Hash Anti Join); NOT IN with a nullable column cannot, and becomes a slow SubPlan. Predicate pushdown: WHERE conditions move into subqueries and views, and into the scan of each partition, which lets partition pruning skip partitions at plan time or at run time (Subplans Removed: N), covered in Partitioning.
WITH recent AS (SELECT * FROM orders WHERE created_at > now() - '7 days')
SELECT * FROM recent WHERE customer_id = 5;
1 PG 12+ default: folded -> Index Scan orders (customer_id = 5 AND created_at > ...)
2 AS MATERIALIZED: CTE Scan recent (Filter: customer_id = 5) over all 7 days of orders
3 PG 11 and older: same as line 2, always| Engine | CTE default | Subquery handling |
|---|---|---|
| PostgreSQL 12+ | Inlined if referenced once and pure; MATERIALIZED / NOT MATERIALIZED | Semi/anti-join pull-up; NOT IN stays a SubPlan |
| MySQL 8 | Derived tables/CTEs merged or materialised; MERGE / NO_MERGE hints; derived condition pushdown | Semijoin strategies (FIRSTMATCH, LOOSESCAN, materialization, duplicate weedout) |
| SQL Server | CTEs always inlined (no materialisation) | Apply operators, semi-join conversion |
| Oracle | Inlined or materialised (MATERIALIZE / INLINE hints) | Subquery unnesting (UNNEST / NO_UNNEST) |
Reading EXPLAIN
How to read a plan Must-know
In plain words: read the shape from the top (the root returns the result), read the execution from the most indented nodes outwards, and on every node compare the estimated rows with the actual rows.
Common misunderstanding: "The node with the biggest actual time is the problem." Times are inclusive of children. The cause is usually the lowest node whose estimate is wrong by an order of magnitude; everything above it is a consequence.
Definition: each line is a node; -> marks a child. cost=startup..total rows=N width=W is the estimate; (actual time=startup..total rows=N loops=L) is the measurement. "the loops value reports the total number of executions of the node, and the actual time and rows values shown are averages per-execution", so multiply by loops for totals but compare per-loop rows with the estimate. Buffers: shared hit=36 read=6 means 36 pages from shared buffers and 6 from the OS or disk; dirtied counts pages this query modified, written counts pages it had to evict and write; temp read/written are spill files; local are temp tables. In the PostgreSQL 19 manual, "The ANALYZE option implicitly enables the BUFFERS option."
a method in six steps
1 EXPLAIN (ANALYZE, BUFFERS, SETTINGS) <query>; wrap writes in BEGIN ... ROLLBACK
2 compare Planning Time vs Execution Time planning-bound queries need fewer joins or prepared plans
3 walk up from the leaves: est rows vs actual rows x loops
4 stop at the first node off by 10x or more that is the root cause
5 ask why: stale stats? correlation? function? LIKE? generic plan? type mismatch?
6 fix the input, re-run, check the whole tree changed as predictedEXPLAIN options (PostgreSQL) Must-know
| Option | What it adds | Notes |
|---|---|---|
ANALYZE | Executes; actual time, rows, loops | Side effects happen; implies BUFFERS in current releases |
BUFFERS | shared/local/temp hit, read, dirtied, written; planning buffers | The I/O story of each node |
VERBOSE | Output column lists, schema-qualified names, worker detail, query identifier | Needed to see what a node projects |
SETTINGS | "Include information on configuration parameters." Only planner-affecting settings that differ from defaults | Catches a forgotten enable_nestloop = off |
WAL | "Include information on WAL record generation." records, FPI, bytes | For INSERT/UPDATE/DELETE |
GENERIC_PLAN | Allows $1 placeholders, shows the generic plan | Cannot combine with ANALYZE |
SERIALIZE | Cost of converting output to text/binary for the client | Big jsonb/TOAST columns |
MEMORY | Planner memory consumption | Huge IN lists, many partitions |
TIMING | Per-node timing (on with ANALYZE) | TIMING OFF reduces clock overhead |
SUMMARY | Planning/Execution Time lines | |
COSTS | Estimated costs and rows (default on) | COSTS OFF for stable test output |
IO | I/O detail for scan nodes (PostgreSQL 19) | |
FORMAT | TEXT, JSON, XML, YAML | FORMAT JSON for tools (explain.dalibo.com, the Go snippet below) |
Node fields you will meet Important
| Field | Meaning | What to do with it |
|---|---|---|
Filter: / Rows Removed by Filter: | Condition applied after reading the row | Large removals on few results: index or predicate problem |
Index Cond: | Condition used to search the index | Absent where you expected it: function or type mismatch |
Recheck Cond: / Heap Blocks: exact= lossy= | Bitmap recheck; lossy pages | Lossy: raise work_mem |
Heap Fetches: | Index-only scan rows checked in the heap | High: VACUUM to refresh the visibility map |
Hash Cond: / Merge Cond: / Join Filter: | Join keys / extra join condition | Join Filter removing most rows: missing join key |
Buckets: Batches: Memory Usage: | Hash table size and spills | Batches > 1: spill |
Sort Method: Sort Key: Presorted Key: | Sort algorithm and keys | external merge: spill |
Workers Planned / Launched | Parallelism requested / obtained | Launched < planned: worker pool exhausted |
Subplans Removed: / never executed | Run-time partition pruning / node skipped | Expected |
Cache Hits / Misses / Evictions | Memoize effectiveness | Many misses: Memoize not helping |
JIT: | Compilation counts and timing | JIT time dominates: raise jit_above_cost or disable |
Planning Time / Execution Time | Whole-statement totals | Excludes network and client parsing |
Real scenarios: a Join Filter removing 99% of rows reveals a join on an expression; Heap Fetches equal to rows after a bulk update reveals VACUUM lag; Workers Launched: 0 at peak hour reveals an exhausted worker pool.
Per-engine behaviour
MySQL 8: EXPLAIN, EXPLAIN ANALYZE, hints, histograms, optimizer trace Important
In plain words: MySQL's optimizer is cost-based too, but it shows plans differently (one row per table by default), uses hash joins instead of merge joins, and has its own hint syntax.
Common misunderstanding: "EXPLAIN rows in MySQL are rows returned." The rows column is the estimated rows examined per lookup, and filtered is the estimated percentage that survive the condition.
Definition: EXPLAIN (traditional) gives id, select_type, table, type (ALL, index, range, ref, eq_ref, const), possible_keys, key, key_len, ref, rows, filtered, Extra (Using where, Using index, Using filesort, Using temporary, Using join buffer (hash join)). EXPLAIN FORMAT=TREE prints the iterator tree; FORMAT=JSON the cost details. EXPLAIN ANALYZE "runs a statement and produces EXPLAIN output along with timing and additional, iterator-based, information about how the optimizer's expectations matched the actual execution", and "always uses the TREE output format". Hash joins: "By default, MySQL (8.0.18 and later) employs hash joins whenever possible"; memory is capped by join_buffer_size, and "When the memory required for a hash join exceeds the amount available, MySQL handles this by using files on disk." Optimizer hints live in /*+ … */ after the verb: JOIN_ORDER, JOIN_FIXED_ORDER, INDEX/NO_INDEX, BKA, BNL, MERGE/NO_MERGE, SEMIJOIN, SET_VAR(...), MAX_EXECUTION_TIME(ms); note HASH_JOIN/NO_HASH_JOIN "have no effect in MySQL 8.4; use BNL or NO_BNL instead". Histograms (ANALYZE TABLE t UPDATE HISTOGRAM ON c WITH 64 BUCKETS, types singleton and equi-height) are "useful primarily for nonindexed columns", because for indexed columns index dives give better estimates. The optimizer trace (SET optimizer_trace = 'enabled=on', then read INFORMATION_SCHEMA.OPTIMIZER_TRACE) shows every considered access path and its cost as JSON.
MySQL session
1 SET optimizer_trace = 'enabled=on';
2 SELECT ... FROM orders JOIN customers ...;
3 SELECT TRACE FROM INFORMATION_SCHEMA.OPTIMIZER_TRACE\G
4 -> "rows_estimation", "considered_execution_plans", "chosen": true/false with "cost"
5 SET optimizer_trace = 'enabled=off';-- MySQL 8.4
EXPLAIN FORMAT=TREE
SELECT o.id FROM orders o JOIN customers c ON c.id = o.customer_id WHERE c.country = 'DE';
EXPLAIN ANALYZE
SELECT /*+ JOIN_ORDER(c, o) MAX_EXECUTION_TIME(2000) */ o.id
FROM orders o JOIN customers c ON c.id = o.customer_id WHERE c.country = 'DE';
-- -> Nested loop inner join (cost=... rows=...) (actual time=0.05..12.3 rows=4210 loops=1)
ANALYZE TABLE customers UPDATE HISTOGRAM ON country WITH 64 BUCKETS;
SELECT HISTOGRAM FROM information_schema.COLUMN_STATISTICS
WHERE TABLE_NAME = 'customers' AND COLUMN_NAME = 'country';SQL Server: execution plans and parameter sniffing Important
SQL Server shows an estimated plan (SET SHOWPLAN_XML ON) or an actual plan ("select Include Actual Execution Plan", or "use SET STATISTICS XML to return execution plan information for each statement after executing it"); SET STATISTICS IO, TIME ON gives logical/physical reads per table. Operators are Index Seek, Index Scan, Key Lookup, Nested Loops, Hash Match, Merge Join, Adaptive Join, Sort, Stream Aggregate, Parallelism. Plans are cached instance-wide and reused across sessions, so parameter sniffing is the classic SQL Server incident: a procedure first called with a rare value caches a seek plan that every later caller with a common value reuses. Remedies: OPTION (RECOMPILE) ("turns parameter and local variables into compile-time constants"), OPTIMIZE FOR (@p = …) or OPTIMIZE FOR UNKNOWN, Query Store plan forcing, and Parameter Sensitive Plan optimization, which needs "database compatibility level 160 or higher" and keeps multiple cached plans per statement.
Oracle, SQLite, MongoDB, CockroachDB, Redis Good to know
| Product | How to see the plan | Planner notes |
|---|---|---|
| Oracle | EXPLAIN PLAN FOR … + DBMS_XPLAN.DISPLAY; actuals with DBMS_XPLAN.DISPLAY_CURSOR(format => 'ALLSTATS LAST') | Cost-based (CBO), bind peeking, adaptive plans, SQL plan baselines and SQL profiles for stability, rich hints |
| SQLite | EXPLAIN QUERY PLAN (SCAN, SEARCH ... USING INDEX) | Nested-loop joins only; join order by the Next-Generation Query Planner; ANALYZE fills sqlite_stat1/stat4 |
| MongoDB | db.c.find(...).explain("executionStats"): winningPlan, rejectedPlans, totalKeysExamined, totalDocsExamined | Candidate plans race for a trial period; the winner is cached per query shape |
| CockroachDB | EXPLAIN, EXPLAIN ANALYZE, EXPLAIN ANALYZE (DEBUG) bundle | Cost-based optimizer with automatic table statistics; plans are distributed across nodes |
| Redis | No query planner | Commands have documented complexity (O(1), O(log N)); "planning" is your data-structure choice |
Mechanics
Every planner knob Must-know
| Knob (PostgreSQL) | Default | Scope you should use | Effect |
|---|---|---|---|
default_statistics_target | 100 | Per column via SET STATISTICS | MCV/histogram size, sample size |
random_page_cost / seq_page_cost | 4.0 / 1.0 | Server or tablespace | Index vs seq scan balance |
effective_cache_size | 4GB | Server | Index scan attractiveness |
work_mem | 4MB | Role or SET LOCAL | Per sort/hash node memory |
hash_mem_multiplier | 2.0 | Server | Hash nodes get work_mem × this |
join_collapse_limit / from_collapse_limit | 8 / 8 | SET LOCAL | How far join order is searched |
geqo_threshold / geqo | 12 / on | Server | When GEQO takes over |
plan_cache_mode | auto | Role, database, SET LOCAL | Generic vs custom plans |
max_parallel_workers_per_gather | 2 | Role or SET LOCAL | Workers per Gather |
jit, jit_above_cost | off (19), 100000 | Role | JIT on expensive plans |
enable_nestloop, enable_hashjoin, enable_mergejoin, enable_seqscan, enable_indexscan, enable_bitmapscan, enable_sort, enable_incremental_sort, enable_memoize, enable_hashagg, enable_partition_pruning | on | Experiments only | Penalise a node type, not forbid it |
temp_file_limit | -1 (no limit) | Server | Cap temp files per process |
log_temp_files | -1 | Server (e.g. 0) | Log every spill with its size |
statement_timeout | 0 | Role or SET LOCAL | Kills runaway plans |
The manual calls the enable_* flags "a crude tool, but useful": they add a huge cost to a node type, so the planner still uses it when there is no alternative.
Memory: work_mem, batches, spills Must-know
Each sort, hash, bitmap and hash aggregate may use work_mem (hash nodes work_mem × hash_mem_multiplier) before writing temp files. Raising work_mem globally is dangerous because "the total memory used could be many times the value of work_mem": the limit is per node, per query, per parallel worker, per session. A query with 4 hash joins and 2 sorts, 4 workers, 100 sessions can in theory use 6 × 5 × 100 × work_mem. Spills are visible as Batches: > 1, Sort Method: external merge, temp read/written in BUFFERS, temp_blks_written in pg_stat_statements, and LOG: temporary file: path "...", size ... when log_temp_files = 0.
Error codes and messages you will meet Important
| Message | Code | Cause | Fix |
|---|---|---|---|
ERROR: canceling statement due to statement timeout | PostgreSQL 57014 | Bad plan ran past statement_timeout | Fix the estimate; keep the timeout |
ERROR: temporary file size exceeds temp_file_limit (…kB) | PostgreSQL 53400 | Spill larger than the cap | Better plan or SET LOCAL work_mem |
ERROR: out of memory / OOM killer | PostgreSQL 53200 | Many nodes × work_mem × sessions | Lower global work_mem, pool connections |
ERROR: EXPLAIN options ANALYZE and GENERIC_PLAN cannot be used together | PostgreSQL 22023 (invalid parameter value) | Mixed options | Use one or the other |
Query execution was interrupted, maximum statement execution time exceeded | MySQL 3024 | MAX_EXECUTION_TIME / max_execution_time | Fix plan or raise the limit for that query |
Out of sort memory, consider increasing server sort buffer size | MySQL 1038 | sort_buffer_size too small for one row | Raise per session |
Operator used tempdb to spill data (plan warning) | SQL Server | Memory grant too small (estimate too low) | Update statistics; memory grant feedback |
Finding candidates: pg_stat_statements and auto_explain Must-know
pg_stat_statements "provides a means for tracking planning and execution statistics of all SQL statements executed by a server". It must be in shared_preload_libraries (restart), then CREATE EXTENSION pg_stat_statements. Queries are normalised (constants become $1) and grouped by queryid; useful columns are calls, total_exec_time, mean_exec_time, rows, shared_blks_hit, shared_blks_read, shared_blks_dirtied, temp_blks_written, and plans/total_plan_time with pg_stat_statements.track_planning. Rank by total_exec_time to find what to explain.
auto_explain "provides a means for logging execution plans of slow statements automatically, without having to run EXPLAIN by hand." "the default behavior is to do nothing, so you must set at least auto_explain.log_min_duration". With auto_explain.log_analyze on, "per-plan-node timing occurs for all statements executed, whether or not they run long enough to actually get logged. This can have an extremely negative impact on performance"; turn auto_explain.log_timing off and use auto_explain.sample_rate to reduce it. Other knobs: log_buffers, log_wal, log_settings, log_nested_statements, log_format = json.
-- postgresql.conf (restart for shared_preload_libraries)
-- shared_preload_libraries = 'pg_stat_statements,auto_explain'
-- auto_explain.log_min_duration = '500ms'
-- auto_explain.log_analyze = on
-- auto_explain.log_buffers = on
-- auto_explain.log_timing = off
-- auto_explain.log_settings = on
-- auto_explain.sample_rate = 0.1
-- auto_explain.log_format = json
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT queryid, calls, round(total_exec_time) AS total_ms, round(mean_exec_time::numeric, 2) AS mean_ms,
shared_blks_read, temp_blks_written, left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;The Go equivalent, which ranks statements and also scopes settings to one transaction:
// Package tuning finds the statements worth explaining and scopes planner
// settings to one transaction instead of the whole server.
package tuning
import (
"context"
"database/sql"
"fmt"
)
// Statement is one normalised query from pg_stat_statements.
type Statement struct {
QueryID int64
Query string
Calls int64
TotalExecMs float64
MeanExecMs float64
Rows int64
SharedHit int64
SharedRead int64
TempWritten int64
HitRatioPct float64
MsPerCallRead float64
}
// topSQL ranks by total execution time: a 2 ms query called a million times
// costs more than a 3 s report run once a day.
const topSQL = `
SELECT queryid, query, calls, total_exec_time, mean_exec_time, rows,
shared_blks_hit, shared_blks_read, temp_blks_written,
100.0 * shared_blks_hit / nullif(shared_blks_hit + shared_blks_read, 0)
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
ORDER BY total_exec_time DESC
LIMIT $1`
// TopStatements returns the n most expensive statements. The extension must
// be in shared_preload_libraries and created with CREATE EXTENSION.
func TopStatements(ctx context.Context, db *sql.DB, n int) ([]Statement, error) {
rows, err := db.QueryContext(ctx, topSQL, n)
if err != nil {
return nil, fmt.Errorf("pg_stat_statements: %w", err)
}
defer rows.Close()
var out []Statement
for rows.Next() {
var s Statement
var ratio sql.NullFloat64
if err := rows.Scan(&s.QueryID, &s.Query, &s.Calls, &s.TotalExecMs, &s.MeanExecMs,
&s.Rows, &s.SharedHit, &s.SharedRead, &s.TempWritten, &ratio); err != nil {
return nil, err
}
s.HitRatioPct = ratio.Float64
if s.Calls > 0 {
s.MsPerCallRead = float64(s.SharedRead) / float64(s.Calls)
}
out = append(out, s)
}
return out, rows.Err()
}
// Setting is one planner or memory parameter, applied with SET LOCAL
// semantics so it ends with the transaction and never leaks to the next
// user of a pooled connection.
type Setting struct {
Name string
Value string
}
// ReportSettings is a typical profile for one heavy reporting query.
var ReportSettings = []Setting{
{"work_mem", "256MB"}, // per sort/hash node, not per query
{"plan_cache_mode", "force_custom_plan"}, // skewed parameters: plan per value
{"max_parallel_workers_per_gather", "4"}, // allow a wider Gather
{"statement_timeout", "30s"}, // a bad plan fails fast (57014)
}
// WithSettings runs fn in a transaction where each setting is applied with
// set_config(name, value, is_local => true), the function form of SET LOCAL.
// Parameters are bound, so no name or value is concatenated into SQL.
func WithSettings(ctx context.Context, db *sql.DB, settings []Setting, fn func(*sql.Tx) error) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
for _, s := range settings {
if _, err := tx.ExecContext(ctx, `SELECT set_config($1, $2, true)`, s.Name, s.Value); err != nil {
return fmt.Errorf("set %s: %w", s.Name, err)
}
}
if err := fn(tx); err != nil {
return err
}
return tx.Commit()
}MySQL's equivalents are the slow query log (long_query_time, log_queries_not_using_indexes) and performance_schema.events_statements_summary_by_digest; SQL Server's is Query Store (sys.query_store_runtime_stats), which also keeps plan history and can force a plan.
Plan stability: hints, pg_hint_plan, pg_plan_advice Important
PostgreSQL core has no hints by design. Two add-ons fill the gap. pg_hint_plan (ossc-db/pg_hint_plan) reads hints from a leading comment: scan hints (SeqScan(t), IndexScan(t idx), BitmapScan, IndexOnlyScan), join-method hints (NestLoop(a b), HashJoin(a b), MergeJoin(a b)), Leading((a b) c) for join order, Rows(a b #1000) to correct an estimate, Parallel(t 4 hard), and Set(work_mem "256MB"); its README admits the planner "may not count some data properties, like correlation between columns." PostgreSQL 19 ships the contrib module pg_plan_advice: EXPLAIN (PLAN_ADVICE) prints an advice string such as JOIN_ORDER(f d) HASH_JOIN(d), and setting pg_plan_advice.advice reapplies it. The manual says it "is intended to allow stabilization of plan choices that the user believes to be good", and warns that if the data distribution changes, "a very poor plan may be chosen."
-- pg_hint_plan: correct the estimate rather than dictate the join
/*+ Rows(a c #48000) */
SELECT ... FROM addresses a JOIN customers c ON c.id = a.customer_id WHERE a.country = 'DE';
-- pg_plan_advice (PostgreSQL 19 contrib)
EXPLAIN (PLAN_ADVICE) SELECT ...; -- prints e.g. JOIN_ORDER(a c) HASH_JOIN(c)
SET pg_plan_advice.advice = 'JOIN_ORDER(a c) HASH_JOIN(c)';Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Stale statistics after load | ANALYZE in the job | Last step of every load/backfill | Cheap (sample), fixes many plans at once | Locks nothing heavy; sample variance |
| Correlated columns | CREATE STATISTICS | (dependencies, mcv) on the pair | Fixes estimate at the source | Only equality/IN for dependencies; one more ANALYZE cost |
| Function on column | Expression statistics or index | ON (lower(email)) | Planner gets a distribution | Index costs writes; statistics alone do not speed the scan |
| Nested-loop disaster | Fix outer estimate | Stats, predicate rewrite | Plan adapts to data changes | Needs diagnosis |
| Same, emergency | Pin a plan | SET LOCAL enable_nestloop = off, pg_hint_plan, pg_plan_advice | Immediate | Freezes; review when data changes |
| Sort/hash spill | Scoped memory | SET LOCAL work_mem | No global OOM risk | Per transaction code change |
| Generic plan regression | Custom plans | plan_cache_mode = force_custom_plan for role/tx | Plan per value | Planning cost each call |
| CTE fence | NOT MATERIALIZED | Let filters push down | Uses indexes | Re-evaluated if referenced twice |
| Planning too slow | Fewer joins / prepared statements | Split query, join_collapse_limit | Bounded planning time | Possibly worse plan |
| Huge IN list | Array parameter | = ANY($1) | One parameter, stable text in pg_stat_statements | Same estimate quality |
Stale statistics after a bulk load
COPY orders FROM '/data/orders.csv' WITH (FORMAT csv);
ANALYZE orders; -- statistics now describe the new data
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE tenant_id = 42;Go: the existing helper refreshes statistics (and creates expression and multivariate statistics) after loads.
// Package after refreshes planner statistics after bulk loads and checks
// plans against reality instead of reading the root cost.
package after
import (
"context"
"database/sql"
"fmt"
)
// statements run after a bulk load or a schema change. ANALYZE takes a
// random sample, so it is cheap compared with the load itself.
var statements = []string{
// Univariate expression statistics. Without them the planner has no
// distribution for lower(email) and falls back to a default selectivity.
// An expression index on lower(email) would also collect these.
`CREATE STATISTICS IF NOT EXISTS customers_email_lower_stx
ON (lower(email)) FROM customers`,
// Multivariate statistics for columns that move together. The planner
// otherwise multiplies their selectivities as if they were independent.
`CREATE STATISTICS IF NOT EXISTS orders_status_channel_stx (dependencies, mcv)
ON status, channel FROM orders`,
// A larger sample and longer MCV list / histogram for a skewed column.
`ALTER TABLE orders ALTER COLUMN created_at SET STATISTICS 500`,
// CREATE STATISTICS only registers interest; ANALYZE collects the data.
`ANALYZE customers, orders`,
}
// RefreshStatistics runs each statement in order.
func RefreshStatistics(ctx context.Context, db *sql.DB) error {
for _, stmt := range statements {
if _, err := db.ExecContext(ctx, stmt); err != nil {
return fmt.Errorf("refresh statistics: %w", err)
}
}
return nil
}Laravel: put ANALYZE at the end of the import job.
// app/Jobs/ImportOrders.php (handle method)
DB::table('orders')->insertUsing($columns, $stagingQuery);
DB::statement('ANALYZE orders');Correlated columns
CREATE STATISTICS addresses_country_vat_stx (dependencies, mcv) ON country, vat_zone FROM addresses;
ANALYZE addresses;
SELECT statistics_name, dependencies FROM pg_stats_ext WHERE tablename = 'addresses';The Before code shows how this hides inside an innocent query; the After code is the same query plus the tooling that finds the bad node.
// Package before bulk-loads orders and immediately runs the report query,
// trusting whatever plan the stale statistics produce.
package before
import (
"context"
"database/sql"
"fmt"
"time"
)
type Order struct {
CustomerID int64
TotalCents int64
CreatedAt time.Time
}
const reportQuery = `
SELECT o.id, o.total_cents, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE lower(c.email) = lower($1)
AND o.created_at >= $2 AND o.created_at < $3
ORDER BY o.created_at`
// Import inserts a large batch and then runs the report straight away.
// There is no ANALYZE: the planner scales the row count to the new table
// size, but pg_statistic (MCV lists, histogram bounds, n_distinct) still
// describes the data before the load. A date range that now holds millions
// of rows can be estimated at a few, and the join is planned for that.
func Import(ctx context.Context, db *sql.DB, batch []Order, email string, from, to time.Time) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
for _, o := range batch {
if _, err := tx.ExecContext(ctx,
`INSERT INTO orders (customer_id, total_cents, created_at) VALUES ($1, $2, $3)`,
o.CustomerID, o.TotalCents, o.CreatedAt); err != nil {
return err
}
}
if err := tx.Commit(); err != nil {
return err
}
// "Checking the plan": QueryRow keeps only the first row of EXPLAIN,
// which is the root node. Its cost says nothing about which child is
// wrong, and without ANALYZE there are no actual row counts to compare.
var top string
if err := db.QueryRowContext(ctx, "EXPLAIN "+reportQuery, email, from, to).Scan(&top); err != nil {
return err
}
fmt.Println("plan:", top)
rows, err := db.QueryContext(ctx, reportQuery, email, from, to)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var id, total int64
var mail string
if err := rows.Scan(&id, &total, &mail); err != nil {
return err
}
}
return rows.Err()
}package after
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"math"
)
// planNode mirrors the keys PostgreSQL emits in EXPLAIN (FORMAT JSON).
// Row counts and loops are floats: recent versions print actual rows with
// two decimals (per-loop averages such as 3.33).
type planNode struct {
NodeType string `json:"Node Type"`
RelationName string `json:"Relation Name"`
PlanRows float64 `json:"Plan Rows"`
ActualRows float64 `json:"Actual Rows"`
ActualLoops float64 `json:"Actual Loops"`
SharedHit int64 `json:"Shared Hit Blocks"`
SharedRead int64 `json:"Shared Read Blocks"`
SortMethod string `json:"Sort Method"`
SortSpaceType string `json:"Sort Space Type"` // "Memory" or "Disk"
HashBatches int64 `json:"Hash Batches"`
Plans []planNode `json:"Plans"`
}
type explainOutput struct {
Plan planNode `json:"Plan"`
PlanningTime float64 `json:"Planning Time"`
ExecutionTime float64 `json:"Execution Time"`
}
// Finding is one suspicious plan node.
type Finding struct {
Node string
Relation string
Estimated float64
Actual float64 // per loop, comparable with Estimated
Loops float64
Hit, Read int64
Reason string
}
// misestimateFactor is the ratio at which an estimate counts as wrong.
const misestimateFactor = 10
// Explain runs the query under EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) and
// returns nodes whose row estimate is off by more than 10x or that spilled
// to disk. ANALYZE really executes the statement, so it runs inside a
// read-only transaction that is always rolled back.
func Explain(ctx context.Context, db *sql.DB, query string, args ...any) ([]Finding, error) {
tx, err := db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
return nil, err
}
defer tx.Rollback()
// One row, one column: a JSON array holding a single {"Plan": ...}.
var raw []byte
err = tx.QueryRowContext(ctx, "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) "+query, args...).Scan(&raw)
if err != nil {
return nil, fmt.Errorf("explain: %w", err)
}
return parse(raw)
}
func parse(raw []byte) ([]Finding, error) {
var out []explainOutput
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("decode plan: %w", err)
}
if len(out) == 0 {
return nil, fmt.Errorf("decode plan: empty output")
}
var findings []Finding
walk(out[0].Plan, "", &findings)
return findings, nil
}
// walk visits the tree depth-first. Plans are read inside-out: the deepest
// node runs first, and the first node whose estimate goes wrong usually
// explains every bad choice above it.
func walk(n planNode, parent string, acc *[]Finding) {
for _, child := range n.Plans {
walk(child, n.NodeType, acc)
}
f := Finding{
Node: n.NodeType, Relation: n.RelationName,
Estimated: n.PlanRows, Actual: n.ActualRows, Loops: n.ActualLoops,
Hit: n.SharedHit, Read: n.SharedRead,
}
if n.SortSpaceType == "Disk" {
f.Reason = fmt.Sprintf("sort spilled to disk (%s): raise work_mem or sort less", n.SortMethod)
*acc = append(*acc, f)
}
if n.HashBatches > 1 {
f.Reason = fmt.Sprintf("hash used %d batches: the hash table did not fit in memory", n.HashBatches)
*acc = append(*acc, f)
}
// Never executed, or BitmapAnd/BitmapOr, which always report 0 rows.
if n.ActualLoops == 0 || n.NodeType == "BitmapAnd" || n.NodeType == "BitmapOr" {
return
}
est := math.Max(n.PlanRows, 1)
act := math.Max(n.ActualRows, 1)
// Under a Limit, or as a Merge Join input, a node can stop early, so
// "fewer rows than estimated" there is not an estimation error.
stopsEarly := parent == "Limit" || parent == "Merge Join"
switch {
case act/est > misestimateFactor:
f.Reason = fmt.Sprintf("underestimate: %.0f rows expected, %.2f per loop", n.PlanRows, n.ActualRows)
*acc = append(*acc, f)
case est/act > misestimateFactor && !stopsEarly:
f.Reason = fmt.Sprintf("overestimate: %.0f rows expected, %.2f per loop", n.PlanRows, n.ActualRows)
*acc = append(*acc, f)
}
}// database/migrations/2026_11_25_000000_add_address_statistics.php (up method)
DB::statement('CREATE STATISTICS IF NOT EXISTS addresses_country_vat_stx (dependencies, mcv) ON country, vat_zone FROM addresses');
DB::statement('ANALYZE addresses');Hash join or sort spills to disk
BEGIN;
SET LOCAL work_mem = '256MB'; -- this transaction only
EXPLAIN (ANALYZE, BUFFERS) SELECT ...; -- Batches: 1, no temp read/written
COMMIT;In Go, tuning.WithSettings(ctx, db, tuning.ReportSettings, fn) above applies set_config(name, value, true), the function form of SET LOCAL. In Laravel:
$rows = DB::transaction(function () use ($from, $to) {
DB::statement("SET LOCAL work_mem = '256MB'");
return DB::select('SELECT customer_id, sum(total) FROM orders WHERE created_at >= ? AND created_at < ? GROUP BY 1', [$from, $to]);
});Generic plan regression
PREPARE q(bigint) AS SELECT * FROM orders WHERE tenant_id = $1;
EXPLAIN EXECUTE q(42); -- "$1" in Index Cond: generic plan
EXPLAIN (GENERIC_PLAN) SELECT * FROM orders WHERE tenant_id = $1;
ALTER ROLE reporting SET plan_cache_mode = force_custom_plan;Go: pgx "automatically prepares and caches prepared statements" by default, so a hot query is a server-side prepared statement. Use tuning.WithSettings with plan_cache_mode, set it per role, or choose a pgx QueryExecMode that does not cache for that query. Laravel with pdo_pgsql prepares a fresh statement for each query call, so each execution is normally a first (custom) plan; generic plans reach a Laravel app mainly through PL/pgSQL functions or a pooler that reuses prepared statements. For those, ALTER ROLE app SET plan_cache_mode = force_custom_plan, or DB::statement("SET LOCAL plan_cache_mode = force_custom_plan") inside a DB::transaction for one query. SQL Server: OPTION (RECOMPILE).
Nested-loop disaster under pressure
BEGIN;
SET LOCAL enable_nestloop = off; -- experiment: what would hash join cost?
EXPLAIN (ANALYZE, BUFFERS, SETTINGS) SELECT ...;
ROLLBACK;If the alternative is much faster, the real fix is the estimate (statistics, predicate shape). Only if that is impossible, pin it with pg_hint_plan (Rows first, join hints second) or pg_plan_advice, and add a test that fails when the plan changes.
Laravel: seeing the plan of an Eloquent query
The Laravel Before code nests whereHas closures without anyone reading the plan; the After code builds the query in one place and an Artisan command explains it.
<?php
// app/Http/Controllers/OrderReportController.php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
final class OrderReportController extends Controller
{
public function index(Request $request): Collection
{
$email = $request->string('email')->lower()->toString();
// Every whereHas becomes a nested EXISTS subquery. lower(email) has no
// statistics of its own, the country/vat_zone pair is correlated, and
// nobody ever looks at the plan the planner picked for all of this.
return Order::query()
->whereHas('customer', function (Builder $customer) use ($email) {
$customer->whereRaw('lower(email) = ?', [$email])
->whereHas('addresses', function (Builder $address) {
$address->where('country', 'DE')
->whereHas('region', fn (Builder $region) => $region->where('vat_zone', 'EU'));
});
})
->whereBetween('created_at', [$request->date('from'), $request->date('to')])
->orderBy('created_at')
->get();
}
}<?php
// app/Queries/OrderReport.php — one place builds the query, so the
// controller and the explain command look at exactly the same SQL.
namespace App\Queries;
use App\Models\Order;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Builder;
final class OrderReport
{
// Same predicates as before. Rewriting whereHas into joins on instinct is
// not the fix; reading the plan and correcting the bad estimate is.
public static function query(string $email, CarbonInterface $from, CarbonInterface $to): Builder
{
return Order::query()
->whereHas('customer', function (Builder $customer) use ($email) {
$customer->whereRaw('lower(email) = lower(?)', [$email])
->whereHas('addresses', function (Builder $address) {
$address->where('country', 'DE')
->whereHas('region', fn (Builder $region) => $region->where('vat_zone', 'EU'));
});
})
->where('created_at', '>=', $from)
->where('created_at', '<', $to)
->orderBy('created_at');
}
}
// app/Console/Commands/ExplainOrderReport.php
namespace App\Console\Commands;
use App\Queries\OrderReport;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
final class ExplainOrderReport extends Command
{
protected $signature = 'report:explain {email} {from} {to} {--factor=10}';
protected $description = 'Run EXPLAIN ANALYZE on the order report and list misestimated or spilling nodes';
public function handle(): int
{
// toBase() applies global scopes and returns the query builder, so
// toSql() and getBindings() describe what Eloquent would really send.
$query = OrderReport::query(
$this->argument('email'),
Carbon::parse($this->argument('from')),
Carbon::parse($this->argument('to')),
)->toBase();
// Bindings inlined: for reading or pasting into psql, never for execution.
$this->line($query->toRawSql());
// explain() prefixes plain EXPLAIN: estimates only, nothing executes.
// On PostgreSQL each returned row is one line of the text plan.
foreach ($query->explain() as $line) {
$this->line($line->{'QUERY PLAN'});
}
// EXPLAIN ANALYZE really runs the statement, so roll it back.
DB::beginTransaction();
try {
$rows = DB::select(
'EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) '.$query->toSql(),
$query->getBindings(),
);
} finally {
DB::rollBack();
}
// One row, one json column holding [{"Plan": {...}, "Execution Time": ...}].
$output = json_decode($rows[0]->{'QUERY PLAN'}, true, flags: JSON_THROW_ON_ERROR)[0];
$findings = [];
$this->walk($output['Plan'], null, (int) $this->option('factor'), $findings);
$this->info(sprintf('Execution time: %.2f ms', $output['Execution Time']));
if ($findings === []) {
$this->info('No misestimated or spilling nodes.');
return self::SUCCESS;
}
$this->table(['Node', 'Relation', 'Estimated', 'Actual/loop', 'Loops', 'Hit', 'Read', 'Why'], $findings);
return self::FAILURE;
}
/**
* Depth-first, children before parents: the deepest wrong estimate is
* usually the cause of every odd choice above it.
*/
private function walk(array $node, ?string $parent, int $factor, array &$findings): void
{
foreach ($node['Plans'] ?? [] as $child) {
$this->walk($child, $node['Node Type'], $factor, $findings);
}
$type = $node['Node Type'];
$row = fn (string $why) => [
$type,
$node['Relation Name'] ?? '',
$node['Plan Rows'],
$node['Actual Rows'] ?? 0,
$node['Actual Loops'] ?? 0,
$node['Shared Hit Blocks'] ?? 0,
$node['Shared Read Blocks'] ?? 0,
$why,
];
if (($node['Sort Space Type'] ?? null) === 'Disk') {
$findings[] = $row("sort spilled to disk ({$node['Sort Method']})");
}
if (($node['Hash Batches'] ?? 1) > 1) {
$findings[] = $row("hash split into {$node['Hash Batches']} batches");
}
// Never executed, or BitmapAnd/BitmapOr, which always report 0 rows.
if (($node['Actual Loops'] ?? 0) == 0 || in_array($type, ['BitmapAnd', 'BitmapOr'], true)) {
return;
}
// Actual Rows is a per-loop average, directly comparable with Plan Rows.
$estimated = max($node['Plan Rows'], 1);
$actual = max($node['Actual Rows'], 1);
// A node under Limit or feeding a Merge Join may stop early on purpose.
$stopsEarly = in_array($parent, ['Limit', 'Merge Join'], true);
if ($actual / $estimated > $factor) {
$findings[] = $row('underestimate');
} elseif ($estimated / $actual > $factor && ! $stopsEarly) {
$findings[] = $row('overestimate');
}
}
}explain() comes from the ExplainsQueries trait and runs 'EXPLAIN '.$sql with the bindings, so on PostgreSQL it gives estimates only. The Eloquent builder forwards explain, toSql, toRawSql and getBindings through its $passthru list. The 13.x docs document dumpRawSql()/ddRawSql(), which "dump the query's SQL with all parameter bindings properly substituted"; use toRawSql() only for reading, and pass toSql() plus getBindings() to execute. DB::listen and DB::whenQueryingForLongerThan find which queries deserve this.
Choosing a fix
| Situation | First move | Second move | Avoid | Why |
|---|---|---|---|---|
| Slow query after deploy, no data change | Compare plans before/after (auto_explain logs) | Check SETTINGS, new predicates | Adding indexes blindly | Usually a query-shape change |
| Slow query after data load | ANALYZE | Raise statistics target on skewed columns | Hints | Estimates are stale |
| Estimate wrong on AND of two columns | CREATE STATISTICS | Composite index if also selective | enable_* flags | Independence assumption |
| Estimate wrong on expression | Expression statistics/index | Rewrite predicate to bare column | Casting in app | No distribution for the function |
| Spill to disk | SET LOCAL work_mem | Reduce rows earlier (filter, pre-aggregate) | Global work_mem raise | Memory multiplies per node and session |
| Fast in psql, slow in app | EXPLAIN EXECUTE / GENERIC_PLAN | plan_cache_mode per role | Disabling prepared statements globally | Generic plan |
| 15-table report | Read model / materialized view | join_collapse_limit + written order | GEQO tuning | Search space |
| OLTP query with JIT time | jit = off for role | Fix the estimate | Leaving JIT on globally | Compilation overhead |
| MySQL bad join order | Histograms + ANALYZE TABLE | JOIN_ORDER hint | STRAIGHT_JOIN everywhere | Estimates first |
| SQL Server sniffing | OPTION (RECOMPILE) on that statement | PSP (compat 160), Query Store forcing | Clearing the whole plan cache | Per-statement fix |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One database, one planner, so every problem is reproducible with EXPLAIN (ANALYZE, BUFFERS) against a production-sized copy. The simplest correct setup: pg_stat_statements and auto_explain (sampled, log_timing = off) on from day one, ANALYZE in every import job, statement_timeout per role, and one class per heavy query (as in the Laravel After snippet) so the controller, the job and the explain command share the same SQL. Example: a Laravel shop whose order report regressed after a CSV import; auto_explain logged a nested loop with loops=48210, and an ANALYZE plus a CREATE STATISTICS in the import job fixed it permanently.
Modular monolith and multiple databases
Modules that share one PostgreSQL still share one planner configuration and one work_mem budget. Give each module its own role and set planner knobs on the role (ALTER ROLE reporting SET work_mem = '128MB', then the same for plan_cache_mode and jit, one setting per statement) so the reporting module cannot starve the checkout module. Cross-module joins are where plans surprise you: a module boundary often becomes a view, and views flatten into the caller's join search, pushing it past join_collapse_limit. Example: a billing module's view joined by the analytics module produced a 13-way join and a GEQO plan that changed daily; replacing the view with a materialized view refreshed nightly made it stable.
Microservices
Each service owns its database and its planner; no plan spans services. Joins you used to do in SQL become API calls or event-fed read models, and the classic nested-loop disaster reappears at the application level as N+1 HTTP calls (see ORM Pitfalls). Example: an order service calls customer service once per order line for a 2,000-line export; the "plan" is a nested loop over HTTP. The fix mirrors the database's: batch (a hash join) with GET /customers?ids=..., or a local read model of customers fed by events (a materialised join). Keep pg_stat_statements per service and propagate trace IDs so a slow endpoint maps to one queryid.
Distributed data: replicas, caches and distributed SQL
Read replicas have their own statistics only through replication: ANALYZE runs on the primary and its results replicate, but a replica's buffer cache differs, so shared read versus hit differ for the same plan. auto_explain and pg_stat_statements are per instance; collect from replicas too. A cache in front of the database hides slow plans until the cache is cold (deploys, evictions), when every miss runs the bad plan at once. In distributed SQL (CockroachDB, YugabyteDB, Spanner), the planner also chooses where to run each fragment, and a "hash join" may mean shipping rows between nodes; the costs include network. Sharded PostgreSQL with Citus pushes down whole queries when they filter on the distribution key and otherwise plans a distributed join with repartitioning.
Scaling path: 1×, 10×, 100×
| Load | What breaks in planning | Change |
|---|---|---|
| 1× | Nothing visible; estimates loose but tables small | pg_stat_statements, auto_explain sampled, ANALYZE in loads |
| 10× | Nested loops on misestimates, spills, generic-plan regressions, out-of-range timestamps | Extended statistics, per-role work_mem, plan_cache_mode, statistics targets on skewed columns |
| 100× | Planning time on wide joins, parallel worker exhaustion, partition counts in the thousands, plan flips after auto-analyze | Partitioning with pruning, read models, pg_plan_advice for the few critical queries, plan-regression tests in CI, analytical store for reports |
Lab
Setup (PostgreSQL 16 or later; outputs are typical shapes, numbers will differ):
-- docker run --name pg -e POSTGRES_PASSWORD=pg -d postgres:18 && docker exec -it pg psql -U postgres
CREATE TABLE customers (id bigint PRIMARY KEY, email text, country text, vat_zone text);
CREATE TABLE orders (id bigserial PRIMARY KEY, customer_id bigint, tenant_id int, status text, total numeric, created_at timestamptz);
ALTER TABLE customers SET (autovacuum_enabled = off); -- so the lab controls ANALYZE
ALTER TABLE orders SET (autovacuum_enabled = off);
INSERT INTO customers
SELECT g, 'user' || g || '@example.com',
CASE WHEN g % 10 = 0 THEN 'DE' ELSE 'US' END,
CASE WHEN g % 10 = 0 THEN 'EU' ELSE 'NA' END -- vat_zone is a function of country
FROM generate_series(1, 200000) g;
INSERT INTO orders (customer_id, tenant_id, status, total, created_at)
SELECT 1 + (g % 200000),
CASE WHEN g % 10 < 9 THEN 42 ELSE g % 1000 END, -- tenant 42 owns 90%
(ARRAY['paid','shipped','pending'])[1 + g % 3], g % 500, now() - (g % 365) * interval '1 day'
FROM generate_series(1, 2000000) g;
CREATE INDEX ON orders (tenant_id);
CREATE INDEX ON orders (customer_id);- Before and after ANALYZE.
EXPLAIN SELECT * FROM orders WHERE tenant_id = 42;
-- no statistics yet: rows estimate is a default guess, e.g. rows=10500 -> Bitmap Heap Scan
ANALYZE customers, orders;
EXPLAIN SELECT * FROM orders WHERE tenant_id = 42;
-- rows=1800000 (MCV knows 90%) -> Seq Scan (or Parallel Seq Scan)
SELECT most_common_vals, most_common_freqs FROM pg_stats WHERE tablename = 'orders' AND attname = 'tenant_id';- Correlated columns, then CREATE STATISTICS.
EXPLAIN ANALYZE SELECT * FROM customers WHERE country = 'DE' AND vat_zone = 'EU';
-- Seq Scan ... (rows=2000) (actual rows=20000) 0.1 * 0.1 * 200000 = 2000 estimated, 10x low
CREATE STATISTICS customers_cv_stx (dependencies, mcv) ON country, vat_zone FROM customers;
ANALYZE customers;
EXPLAIN ANALYZE SELECT * FROM customers WHERE country = 'DE' AND vat_zone = 'EU';
-- Seq Scan ... (rows=20000) (actual rows=20000)- Join algorithms side by side.
EXPLAIN (ANALYZE, BUFFERS) SELECT o.id FROM orders o JOIN customers c ON c.id = o.customer_id WHERE c.country = 'DE';
-- Hash Join, Hash Cond: (o.customer_id = c.id)
BEGIN; SET LOCAL enable_hashjoin = off;
EXPLAIN (ANALYZE, BUFFERS) SELECT o.id FROM orders o JOIN customers c ON c.id = o.customer_id WHERE c.country = 'DE';
-- Merge Join or Nested Loop with Index Scan on orders_customer_id_idx loops=20000
ROLLBACK;- Watch a hash join spill.
BEGIN;
SET LOCAL work_mem = '64kB';
SET LOCAL max_parallel_workers_per_gather = 0;
EXPLAIN (ANALYZE, BUFFERS) SELECT o.id, c.email FROM orders o JOIN customers c ON c.id = o.customer_id;
-- Hash Buckets: ... Batches: 64 Memory Usage: ...kB
-- Buffers: shared hit=... read=..., temp read=... written=...
SET LOCAL work_mem = '256MB';
EXPLAIN (ANALYZE, BUFFERS) SELECT o.id, c.email FROM orders o JOIN customers c ON c.id = o.customer_id;
-- Batches: 1, no temp blocks
ROLLBACK;- Generic vs custom plan switch.
PREPARE q(int) AS SELECT count(*) FROM orders WHERE tenant_id = $1;
EXPLAIN EXECUTE q(7); -- run 6 times; first five show "tenant_id = 7" (custom)
EXPLAIN EXECUTE q(7);
EXPLAIN EXECUTE q(7);
EXPLAIN EXECUTE q(7);
EXPLAIN EXECUTE q(7);
EXPLAIN EXECUTE q(42); -- sixth: may show "tenant_id = $1" (generic), an index plan for 1.8M rows
SET plan_cache_mode = force_custom_plan;
EXPLAIN EXECUTE q(42); -- "tenant_id = 42": Seq Scan / Parallel Seq Scan
EXPLAIN (GENERIC_PLAN) SELECT count(*) FROM orders WHERE tenant_id = $1;- CTE folding and the sort spill (bonus).
EXPLAIN WITH r AS (SELECT * FROM orders) SELECT * FROM r WHERE customer_id = 5; -- Index Scan (folded)
EXPLAIN WITH r AS MATERIALIZED (SELECT * FROM orders) SELECT * FROM r WHERE customer_id = 5; -- CTE Scan + Filter
BEGIN; SET LOCAL work_mem = '64kB';
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders ORDER BY total; -- Sort Method: external merge Disk: ...
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders ORDER BY total LIMIT 10; -- Sort Method: top-N heapsort Memory: ...
ROLLBACK;- MySQL comparison (optional).
-- docker run --name my -e MYSQL_ROOT_PASSWORD=my -d mysql:8.4
EXPLAIN FORMAT=TREE SELECT ... ; -- iterator tree, estimates only
EXPLAIN ANALYZE SELECT ... ; -- (actual time=... rows=... loops=...)
SET optimizer_trace = 'enabled=on'; SELECT ... ; SELECT TRACE FROM INFORMATION_SCHEMA.OPTIMIZER_TRACE\GCommon misconceptions
| Belief | Reality |
|---|---|
| Cost is in milliseconds | Cost is in units of a sequential page read; compare only between plans of one query |
| A Seq Scan means a missing index | For a large fraction of rows it is the cheapest plan; check the estimate |
EXPLAIN ANALYZE updates statistics | It executes the statement; ANALYZE (the command) updates statistics |
EXPLAIN ANALYZE is read-only | It runs INSERT/UPDATE/DELETE for real; wrap in BEGIN … ROLLBACK |
| Nested loops are always bad | With a small outer side and an index they are the fastest join and return rows first |
CREATE STATISTICS takes effect immediately | It registers interest; ANALYZE collects |
| A CTE is always an optimisation fence | Only before PostgreSQL 12, or with MATERIALIZED, or when referenced twice |
Raising work_mem globally is safe | It is per node, per worker, per session; memory multiplies |
actual rows is the total | It is per loop; multiply by loops |
| Hints are the normal tuning tool | They freeze yesterday's plan; fix estimates first |
| Fast in psql means fast in the app | The app may run a generic plan through a prepared statement |
| More parallel workers is always faster | Workers cost setup; many groups or small tables lose; workers may not launch |
| JIT always helps | It costs compile time; harmful on short queries with inflated estimates |
MySQL rows is rows returned | It is estimated rows examined per lookup; see filtered |
Cheat sheet
| Topic | Remember |
|---|---|
| First command | EXPLAIN (ANALYZE, BUFFERS, SETTINGS); writes inside BEGIN … ROLLBACK |
| Where to look | Lowest node with estimated vs actual rows off by 10× |
| Per-loop | actual rows and time are per loop; × loops for totals |
| Buffers | hit = cache, read = OS/disk, dirtied/written = changes/evictions, temp = spills |
| Statistics | ANALYZE after loads; pg_stats: null_frac, n_distinct, MCV, histogram, correlation |
| Correlated columns | CREATE STATISTICS (dependencies, mcv) then ANALYZE |
| Functions | Expression statistics or expression index; otherwise 0.5% guess |
| Joins | Nested loop: small outer + index; hash: big equality, work_mem × 2; merge: sorted inputs |
| Spills | Batches > 1, external merge, temp written; fix with SET LOCAL work_mem |
| Join search | join_collapse_limit/from_collapse_limit 8, GEQO at 12 |
| Prepared statements | 5 custom then maybe generic; plan_cache_mode; EXPLAIN (GENERIC_PLAN) |
| Production | pg_stat_statements to rank, auto_explain to capture, log_temp_files to see spills |
| MySQL | EXPLAIN FORMAT=TREE, EXPLAIN ANALYZE, hash join since 8.0.18, /*+ */ hints, histograms, optimizer_trace |
| SQL Server | Actual plan / SET STATISTICS XML; sniffing → OPTION (RECOMPILE), PSP, Query Store |
| Stability | Statistics first; pg_hint_plan Rows / pg_plan_advice last |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A node shows rows=10 estimated and actual rows=10 loops=5000. Is the estimate wrong? Must-know
Answer
Answer: No, per loop it is right: 10 rows per execution. The node produced 50,000 rows in total. If the problem is the 5,000 loops, look at the outer side of the nested loop above it.
2 — Why can WHERE city = 'Berlin' AND zip = '10115' be underestimated, and what fixes it? Important
Answer
Answer: The planner multiplies the two selectivities as if independent, but zip determines city. CREATE STATISTICS … (dependencies, mcv) ON city, zip FROM t followed by ANALYZE t. See Extended statistics.
3 — What does Batches: 32 under a Hash node mean, and where else do you see it? Important
Answer
Answer: The hash table did not fit in work_mem × hash_mem_multiplier, so input was partitioned into 32 batches written to temp files. It also shows as temp read/written in BUFFERS and temp_blks_written in pg_stat_statements.
4 — A query is fast in psql and slow from a Go service using pgx. What is the first hypothesis and how do you test it? Must-know
Answer
Answer: pgx prepares statements, so after five executions PostgreSQL may use a generic plan. Test with PREPARE + six EXPLAIN EXECUTE, or EXPLAIN (GENERIC_PLAN), and try plan_cache_mode = force_custom_plan for that role or transaction.
5 — When does PostgreSQL 12+ inline a CTE, and how do you force each behaviour? Important
Answer
Answer: When it is non-recursive, side-effect-free and referenced once. AS MATERIALIZED forces separate evaluation; AS NOT MATERIALIZED forces folding.
6 — Why is SET work_mem = '1GB' in postgresql.conf dangerous? Must-know
Answer
Answer: The limit applies per sort/hash node, per parallel worker, per session; a few complex queries in parallel can use many gigabytes and trigger the OOM killer. Use SET LOCAL or a role setting for the workload that needs it.
7 — A query joins 14 tables and its plan changes from run to run. Which mechanism is involved? Good to know
Answer
Answer: With 12 or more FROM items PostgreSQL uses GEQO, a randomised search. Also join_collapse_limit (8) stops reordering beyond 8 explicit joins. Keep the query smaller, set the order explicitly, or move it to a read model.
8 — What does Heap Fetches: 90000 on an Index Only Scan returning 100,000 rows tell you? Important
Answer
Answer: Most pages were not marked all-visible, so the scan checked the heap anyway. VACUUM the table to refresh the visibility map (MVCC & VACUUM).
9 — In MySQL 8.4, how do you see actual rows per operator, and how do you influence join order? Good to know
Answer
Answer: EXPLAIN ANALYZE (always TREE format). Influence order with the JOIN_ORDER or JOIN_FIXED_ORDER optimizer hints; HASH_JOIN hints have no effect in 8.4.
10 — What is parameter sniffing in SQL Server and two ways to deal with it? Good to know
Answer
Answer: The plan is compiled with the first sniffed parameter values and reused for all others. Use OPTION (RECOMPILE), OPTIMIZE FOR, Query Store plan forcing, or Parameter Sensitive Plan optimization at compatibility level 160.
11 — Why should auto_explain.log_timing usually be off in production when log_analyze is on? Important
Answer
Answer: With log_analyze, per-node instrumentation runs for every statement, logged or not; reading the clock per node is the expensive part. Row counts without timing still reveal misestimates.
Glossary
| Term | Meaning |
|---|---|
| Planner / optimizer | Component that chooses the execution plan from candidate paths by estimated cost |
| Parse / rewrite | Stages that build the parse tree and expand views and rules before planning |
| Path | Cut-down plan representation the PostgreSQL planner costs and compares |
| Plan tree | Tree of physical operators the executor runs |
| Volcano / iterator model | Each operator implements next(); parents pull rows from children |
| Cost | Estimated work in units of one sequential page read |
seq_page_cost / random_page_cost | Cost of a sequential / random page read (1.0 / 4.0) |
cpu_tuple_cost / cpu_index_tuple_cost / cpu_operator_cost | CPU cost per row / index entry / operator (0.01 / 0.005 / 0.0025) |
effective_cache_size | Planner's assumption of available cache; allocates nothing |
| Start-up cost | Cost before the first row is returned |
| Selectivity | Fraction of rows a condition keeps |
| Cardinality estimate | Estimated number of rows a node returns |
ANALYZE | Command that samples a table and stores statistics |
pg_stats | View over pg_statistic with per-column statistics |
null_frac | Fraction of NULLs in a column |
n_distinct | Distinct values; negative = fraction of rows |
most_common_vals (MCV) | Most frequent values with their frequencies |
histogram_bounds | Equal-population bucket boundaries over non-MCV values |
correlation | Agreement between physical row order and column order |
default_statistics_target | Default size of MCV list and histogram (100) |
CREATE STATISTICS | Extended statistics on column groups or expressions |
ndistinct / dependencies / mcv (extended) | Group distinct counts / functional dependencies / multi-column MCV |
| Seq Scan | Full table read in physical order |
| Index Scan | Index traversal with heap fetch per row |
| Index Only Scan | Answer from index; heap checked only for not-all-visible pages |
Heap Fetches | Rows an index-only scan still checked in the heap |
| Bitmap Index Scan / Bitmap Heap Scan | Collect TIDs into a bitmap, then read heap pages in order |
| Lossy bitmap | Page-level bitmap after exceeding work_mem; requires recheck |
| Nested Loop | Join that runs the inner plan once per outer row |
| Memoize | Cache of inner results for repeated keys in a nested loop |
| Hash Join | Join that builds a hash table from one input and probes it |
| Batches | Partitions of a hash join or aggregate; > 1 means spill |
| Merge Join | Join of two inputs sorted on the key |
work_mem | Memory per sort/hash node before spilling (4MB) |
hash_mem_multiplier | Multiplier on work_mem for hash nodes (2.0) |
| Spill | Writing intermediate data to temp files |
| Incremental Sort | Sort of groups of input already ordered on a key prefix |
| top-N heapsort | Bounded sort that keeps only LIMIT rows |
| HashAggregate / GroupAggregate | Grouping by hash table / over sorted input |
| Partial / Finalize Aggregate | Two-stage aggregation in parallel plans |
| Gather / Gather Merge | Nodes collecting rows from parallel workers (unordered / ordered) |
max_parallel_workers_per_gather | Workers per Gather node (2) |
| JIT | LLVM compilation of expressions and tuple deforming |
jit_above_cost | Estimated cost threshold for JIT (100000) |
join_collapse_limit / from_collapse_limit | Size limits for flattening joins/subqueries into one search (8) |
| GEQO | Genetic Query Optimizer, used at geqo_threshold (12) FROM items |
| Interesting order | Sort order useful to a later operator (System R) |
| Generic plan / custom plan | Plan reusable for any parameter / planned for specific values |
plan_cache_mode | auto, force_custom_plan, force_generic_plan |
| Parameter sniffing | SQL Server term: compiling a cached plan from the first parameter values |
GENERIC_PLAN | EXPLAIN option that plans a $1 query generically |
MATERIALIZED / NOT MATERIALIZED | Force a CTE to be computed separately / folded |
| Subquery unnesting | Rewriting IN/EXISTS subqueries into semi/anti-joins |
| Predicate pushdown | Moving filters into subqueries, views and scans |
| Partition pruning | Skipping partitions at plan or run time |
EXPLAIN options | ANALYZE, BUFFERS, VERBOSE, SETTINGS, WAL, FORMAT JSON, GENERIC_PLAN, SERIALIZE, MEMORY |
loops | Number of times a node executed; actuals are per loop |
| shared hit / read / dirtied / written | Buffer cache hits / reads from OS / pages modified / pages evicted |
| temp read / written | Temp file blocks from spills |
Rows Removed by Filter | Rows read and discarded by a non-index condition |
auto_explain | Contrib module that logs plans of slow statements |
pg_stat_statements | Contrib module aggregating statistics per normalised query |
pg_hint_plan | Third-party extension reading planner hints from comments |
pg_plan_advice | PostgreSQL 19 contrib module to capture and reapply plan advice |
enable_* flags | Planner switches that penalise a node type, for experiments |
MySQL EXPLAIN FORMAT=TREE / EXPLAIN ANALYZE | Iterator tree / executed tree with actual time, rows, loops |
| MySQL optimizer hints | /*+ JOIN_ORDER(...) INDEX(...) BNL(...) SET_VAR(...) */ comments |
| MySQL histogram | Column statistics via ANALYZE TABLE … UPDATE HISTOGRAM (singleton, equi-height) |
optimizer_trace | MySQL JSON trace of the optimizer's decisions |
join_buffer_size | MySQL memory cap for a hash join before disk files |
OPTION (RECOMPILE) | SQL Server hint to compile the statement with current values each time |
| Parameter Sensitive Plan optimization | SQL Server 2022 feature caching several plans per statement |
References
- P. Griffiths Selinger, M. M. Astrahan, D. D. Chamberlin, R. A. Lorie, T. G. Price, "Access Path Selection in a Relational Database Management System", ACM SIGMOD 1979. PDF
- PostgreSQL documentation: Using EXPLAIN, Statistics Used by the Planner, Row Estimation Examples, Controlling the Planner with Explicit JOIN Clauses, The Path of a Query, Planner/Optimizer, Genetic Query Optimizer (61.1, 61.3), Query Planning settings, Resource Consumption,
pg_stats, CREATE STATISTICS, PREPARE, EXPLAIN, WITH Queries, How Parallel Query Works, Parallel Plans, Why JIT, When to JIT, auto_explain, pg_stat_statements, pg_plan_advice, Additional Supplied Modules - PostgreSQL source:
explain.c,tuplesort.c - pg_hint_plan: README, Hints list
- MySQL 8.4 Reference Manual: EXPLAIN Statement, EXPLAIN Output Format, Hash Join Optimization (and the 8.0 version for 8.0.18), Optimizer Hints, Optimizer Statistics (histograms), OPTIMIZER_TRACE table, Tracing the Optimizer
- Microsoft SQL Server: Query Processing Architecture Guide, Display an Actual Execution Plan, Parameter Sensitive Plan optimization
- Go: pgx v5,
database/sql - Laravel 13 documentation: Query Builder, Debugging, Database, Listening for Query Events; framework source:
ExplainsQueries, QueryBuilder::toRawSql, EloquentBuilder