Skip to content

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 forGo to
Tables you can memorise in one minuteEverything in one minute
Why a planner exists and what it tradesWhy the planner exists
System R, Selinger 1979, the Volcano modelWhere it comes from
Each concept with plain words, a timeline, engines and a fixThe concepts, one by one
How to read a plan node by node, every EXPLAIN option and fieldReading EXPLAIN
MySQL, SQL Server, Oracle, SQLite, MongoDB, CockroachDBPer-engine behaviour
Every knob with its default, memory, error codes, auto_explain, pg_stat_statementsMechanics
Stale stats, correlated columns, nested-loop disasters, spills, generic plansSolving the classic problems
Which tool for which situationChoosing a fix
Monolith to distributed systemIn architecture
Reproduce every effect yourselfLab
Wrong beliefs, cheat sheet, self-check, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The pipeline. Unpacked in the pipeline block.

StageWhat happensWhat you can see
ParseGrammar check, raw parse treeSyntax errors (42601)
Analyze + rewriteNames and types resolved, views and rules expandedUnknown column/table errors (42703, 42P01)
Plan (optimize)Candidate paths costed from statistics, cheapest becomes the plan treeEXPLAIN
ExecuteIterator tree pulls rows node by node (Volcano model)EXPLAIN ANALYZE, auto_explain, pg_stat_statements

The operators.

OperatorIn plain wordsGood whenBad when
Seq ScanRead every page in orderLarge fraction of rows, tiny tablesFew rows wanted from a big table
Index ScanWalk index, jump to heap per rowFew rows, or index order serves ORDER BYMany rows: random I/O per row
Index Only ScanAnswer from the index aloneCovered columns, pages all-visibleVisibility map stale: Heap Fetches high
Bitmap Heap ScanCollect row locations, read heap in physical orderMiddle ground; combine indexes with BitmapAnd/BitmapOrBitmap goes lossy under low work_mem
Nested LoopFor each outer row, probe the inner sideSmall outer side, indexed inner, LIMITOuter estimate far too low
Hash JoinBuild hash table from one side, probe with the otherLarge unsorted equality joinsBuild side does not fit: Batches > 1
Merge JoinWalk two sorted inputs togetherBoth sides already orderedExplicit sorts that spill
Sort / Incremental Sort / top-N heapsortFull sort / sort by groups of a presorted prefix / keep only N bestORDER BY, DISTINCT, merge join inputexternal merge Disk:
HashAggregate / GroupAggregateGroup in a hash table / group sorted inputFew groups / input already sortedMany groups under low memory
Gather / Gather MergeCollect rows from parallel workersBig scans and aggregatesTiny queries, many groups

The five things to do.

SituationDo this
A query is slowEXPLAIN (ANALYZE, BUFFERS); find the lowest node where estimated and actual rows differ by 10× or more
Estimates wrong after a loadANALYZE table as the last step of every bulk load or backfill
Two filtered columns move togetherCREATE STATISTICS ... (dependencies, mcv) ON a, b FROM t; ANALYZE t;
Sort or hash spillsRaise work_mem for that transaction with SET LOCAL, not globally
Fast in psql, slow from the appSuspect 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, predictableBetter plan for each value and data shape
Ignores data distributionDepends on fresh, representative statistics
One plan for all parameter values (generic)Plan per parameter value (custom); costs planning time each call
Stable across data changesCan flip to a different plan after ANALYZE or growth
SQLite's nested-loop-only executor, MongoDB's cached winning planPostgreSQL, 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 ​

  1. "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.
  2. "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.
  3. "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 ​

SQL textSELECT ... JOIN1. Parsegrammar checkraw parse tree2. Analyze + Rewriteresolve names, typesexpand views, rules3. Plan (optimizer)paths, costs, join ordercheapest path → plan tree4. Executeiterator treerows to clientEXPLAIN shows the output of step 3; EXPLAIN ANALYZE also runs step 4 and measures itStatisticspg_class, pg_statisticpg_statistic_ext (ANALYZE)Cost constantsseq/random_page_costcpu_*_cost, work_memPlan cacheprepared statements:custom vs genericVolcano / iterator model inside step 4LimitHash JoinSeq Scan ordersHash ← Index Scanparent calls next()child returns one row

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).

text
     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.

EnginePipeline namesPlan cache
PostgreSQLparser, rewriter, planner, executorPer session, for prepared statements
MySQL 8parser, resolver, optimizer, iterator executorNo shared plan cache; prepared statements re-optimise
SQL Serverparse, bind (algebrizer), optimize, executeInstance-wide plan cache, keyed by query text
Oracleparse (hard/soft), optimize, row source generation, executeShared pool (library cache)
SQLitetokenizer/parser, code generator, VDBE bytecodePer 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.

text
     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
ConstantDefault (PostgreSQL 19)Meaning
seq_page_cost1.0One page read in sequence
random_page_cost4.0One non-sequential page read; 1.1–2.0 is common on SSD
cpu_tuple_cost0.01Processing one row
cpu_index_tuple_cost0.005Processing one index entry
cpu_operator_cost0.0025Evaluating one operator or function call
parallel_setup_cost1000Starting parallel workers
parallel_tuple_cost0.1Passing one row from worker to leader
effective_cache_size4GBPlanner'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.

text
     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 s

Real 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).

EngineStatistics objectRefresh
PostgreSQLpg_statistic / pg_stats, pg_statistic_extANALYZE, autovacuum (autovacuum_analyze_scale_factor 0.1)
MySQL InnoDBPersistent index stats (innodb_stats_persistent), histograms in data dictionaryANALYZE TABLE, auto-recalc on ~10% change; histograms only by ANALYZE TABLE ... UPDATE HISTOGRAM
SQL ServerStatistics objects with histogram (≤ 200 steps) + densityAUTO_UPDATE_STATISTICS, UPDATE STATISTICS
OracleDBMS_STATS, histograms (frequency, height-balanced, hybrid)Automatic stats job, DBMS_STATS.GATHER_TABLE_STATS
SQLitesqlite_stat1, sqlite_stat4ANALYZE, PRAGMA optimize
MongoDBNo column histograms; plan chosen by trial executionPlan cache flushed on index or data changes

Fix: SQL ANALYZE orders; after loads; Go and Laravel below in stale statistics.

sql
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.

text
     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 Loop

Real 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.

EngineMulti-column statistics
PostgreSQLCREATE STATISTICS with ndistinct, dependencies, mcv, expressions
MySQLIndex prefix cardinality only for indexed columns; histograms are single-column
SQL ServerMulti-column statistics objects (CREATE STATISTICS ON t(a, b)), density vector for the prefix
OracleColumn groups via DBMS_STATS.CREATE_EXTENDED_STATS, expression statistics
CockroachDBMulti-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 modeTypical predicateWhy the estimate is wrongFix
Correlated columnscity = $1 AND zip = $2Independence assumptionCREATE STATISTICS (dependencies, mcv)
Function on columnlower(email) = $1, date(created_at) = $1No distribution for the expressionExpression statistics or expression index
LIKE / regexname LIKE '%son%'Leading wildcard: default guessTrigram index (pg_trgm) for the scan; accept the estimate
Long IN listsid 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 valuescreated_at > now() - '1h'Histogram ends at last ANALYZEMore frequent ANALYZE; PostgreSQL probes the index end for the actual max
Stale statisticsAfter a bulk loadreltuples and MCV describe old dataANALYZE in the load job
Skewed join keysOne tenant with 90% of rowsJoin estimate uses averagesMCV on join key; per-tenant plans; plan_cache_mode
Type mismatchvarchar_col = 123Cast on column defeats index and statsCompare with correctly typed parameters
text
     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 disk

Real 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.

text
     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)
EngineNames in the plan
PostgreSQLSeq Scan, Index Scan, Index Only Scan, Bitmap Index/Heap Scan, Tid Scan
MySQL EXPLAIN type columnALL (full scan), index (full index), range, ref, eq_ref, const; Using index = covering; Using index condition = ICP
SQL ServerTable Scan / Clustered Index Scan, Index Seek, Key Lookup (heap/clustered fetch)
OracleTABLE ACCESS FULL, INDEX RANGE SCAN, TABLE ACCESS BY INDEX ROWID, INDEX FAST FULL SCAN
SQLite EXPLAIN QUERY PLANSCAN 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 ​

Nested LoopHash JoinMerge Joinouter (small)row 1row 2row 3inner (index)B-tree onjoin keyone probe per outer row (loops=N)Cost ≈ outer rows × inner probeMemory: none extra (Memoize optional)Any join condition, incl. <, LIKEFast first row; good with LIMITFailure modeestimate 10 outer rows, actual 50,000:50,000 index probes, random I/Ofix the estimate, not the join1. buildsmaller input→ hash table2. probeeach row oflarger inputfits in work_mem × hash_mem_multiplier?yes: Batches: 1no: Batches: 8temp filesCost ≈ build + probe (linear)Equality joins onlyFailure modebuild side underestimated: batchesgrow, temp read/written in BUFFERSMySQL: join_buffer_size, disk filesleft, sortedright, sorted135125advance the smaller keyCost ≈ sort(L) + sort(R) + L + RFree if an index gives the orderMergeable (=) conditions onlyOutput stays sorted (interesting order)Failure modeexplicit Sort spills to disk:Sort Method: external mergeMySQL has no merge join

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:

JoinMechanismCost shapeMemoryPicked when
Nested LoopFor each outer row, run the inner plan (ideally an index lookup on the join key); loops on the inner node = outer rowsouter rows × inner costNone (optional Memoize cache, enable_memoize)Small outer side; non-equality conditions (<, LIKE, BETWEEN); LIMIT
Hash JoinHash child builds a table from the (estimated) smaller input; parent probes it with each outer row (Hash Cond:)build + probe, roughly linearwork_mem × hash_mem_multiplier (4 MB × 2.0); beyond that, Batches > 1 and temp filesEquality joins of large unsorted inputs
Merge JoinBoth inputs sorted on the key (index or Sort), merged in one pass (Merge Cond:)sort + linear mergeOnly for the sortsInputs already ordered; output order useful upstream; very large inputs
text
     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.

EngineNested loopHash joinMerge join
PostgreSQLYes, plus MemoizeYes, plus Parallel HashYes
MySQL 8Yes (Block Nested Loop replaced; Batched Key Access optional)Since 8.0.18; memory join_buffer_size, spills to disk filesNo
SQL ServerNested LoopsHash MatchMerge Join; plus Adaptive Join (switches at run time)
OracleNESTED LOOPSHASH JOINSORT MERGE JOIN; adaptive plans
SQLiteOnly nested loop (with automatic indexes)NoNo
MongoDB $lookupPer-document lookup (index on foreignField matters); slot-based engine can hash joinYes 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.

text
     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 vary

Real 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.

EngineSearch strategy and knob
PostgreSQLDP to join_collapse_limit/from_collapse_limit, GEQO at geqo_threshold
MySQLGreedy search bounded by optimizer_search_depth (default 62; 0 means automatic) and optimizer_prune_level; STRAIGHT_JOIN / JOIN_ORDER hint
SQL ServerTransformation-based search that can stop early (plan property "Reason For Early Termination Of Statement Optimization: Time Out")
OracleCost-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).

text
     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
EngineSort spill signal
PostgreSQLSort Method: external merge Disk: 51200kB; temp written in BUFFERS
MySQLUsing filesort in Extra; sort_buffer_size; Sort_merge_passes status
SQL ServerSort warning "Operator used tempdb to spill data" in the actual plan
OracleTEMP 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.

text
     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 rows

Parallel 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.

text
     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)
EngineIntra-query parallelism
PostgreSQLGather / Gather Merge, parallel seq/index/bitmap scans, parallel hash, partial aggregates
MySQLParallel clustered-index reads for SELECT COUNT(*) and CHECK TABLE (innodb_parallel_read_threads); general queries single-threaded
SQL ServerMAXDOP, cost threshold for parallelism, Parallelism (Gather Streams / Repartition Streams) operators
OracleParallel execution with PX servers, PARALLEL hint
CockroachDBDistributed 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.

text
     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 role

Generic 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.

text
     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
EngineParameterised plan behaviourEscape hatch
PostgreSQL5 custom plans, then generic if not much costlierplan_cache_mode, per role/database/transaction
SQL ServerPlan compiled with sniffed values, cached and reusedOPTION (RECOMPILE), OPTIMIZE FOR, Parameter Sensitive Plan optimization (compatibility level 160)
OracleBind variable peeking; adaptive cursor sharing creates bind-sensitive child cursors/*+ BIND_AWARE */, SQL plan baselines
MySQLPrepared statements are re-optimised on each execution; no shared plan cachen/a
MongoDBPlan cache per query shape; entries replanned when performance degradesplanCacheClear

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.

text
     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
EngineCTE defaultSubquery handling
PostgreSQL 12+Inlined if referenced once and pure; MATERIALIZED / NOT MATERIALIZEDSemi/anti-join pull-up; NOT IN stays a SubPlan
MySQL 8Derived tables/CTEs merged or materialised; MERGE / NO_MERGE hints; derived condition pushdownSemijoin strategies (FIRSTMATCH, LOOSESCAN, materialization, duplicate weedout)
SQL ServerCTEs always inlined (no materialisation)Apply operators, semi-join conversion
OracleInlined or materialised (MATERIALIZE / INLINE hints)Subquery unnesting (UNNEST / NO_UNNEST)

Reading EXPLAIN ​

Sort (cost=9120..9122 rows=12) (actual rows=48210 loops=1)Sort Method: external merge Disk: 5120kBNested Loop (rows=12) (actual rows=48210 loops=1)chosen because the planner expected only 12 rowsSeq Scan on addresses (rows=12) (actual rows=48210 loops=1)Filter: (country = 'DE' AND vat_zone = 'EU')Rows Removed by Filter: 951790 Buffers: shared hit=310 read=8030Index Scan using customers_pkey (rows=1) (actual rows=1 loops=48210)Index Cond: (id = addresses.customer_id)Buffers: shared hit=190240 read=2400Planning Time: 0.9 ms Execution Time: 2140 msShape: read top-down (the root returns the result).Execution: inside-out (the most indented nodes produce rows first).Per-loop numbers: actual rows × loops = total rows the node produced.Totals: 48210 loops × 1 row; buffers are already totals.① Start here: first big misestimate12 estimated vs 48210 actual (4000×)correlated columns multiplied as independentfix: CREATE STATISTICS (dependencies, mcv)② Consequence: loops=48210the inner index scan ran once per outer rowa hash join would have read customers once③ Consequence: sort spilledwork_mem sized for 12 rows, got 48210temp read/written appear in BUFFERSBuffers legendshared hit: page found in shared_buffersshared read: fetched from OS cache or diskshared dirtied / written: pages changed / evictedtemp read / written: spill files (sort, hash)

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."

text
     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 predicted

EXPLAIN options (PostgreSQL) Must-know ​

OptionWhat it addsNotes
ANALYZEExecutes; actual time, rows, loopsSide effects happen; implies BUFFERS in current releases
BUFFERSshared/local/temp hit, read, dirtied, written; planning buffersThe I/O story of each node
VERBOSEOutput column lists, schema-qualified names, worker detail, query identifierNeeded to see what a node projects
SETTINGS"Include information on configuration parameters." Only planner-affecting settings that differ from defaultsCatches a forgotten enable_nestloop = off
WAL"Include information on WAL record generation." records, FPI, bytesFor INSERT/UPDATE/DELETE
GENERIC_PLANAllows $1 placeholders, shows the generic planCannot combine with ANALYZE
SERIALIZECost of converting output to text/binary for the clientBig jsonb/TOAST columns
MEMORYPlanner memory consumptionHuge IN lists, many partitions
TIMINGPer-node timing (on with ANALYZE)TIMING OFF reduces clock overhead
SUMMARYPlanning/Execution Time lines
COSTSEstimated costs and rows (default on)COSTS OFF for stable test output
IOI/O detail for scan nodes (PostgreSQL 19)
FORMATTEXT, JSON, XML, YAMLFORMAT JSON for tools (explain.dalibo.com, the Go snippet below)

Node fields you will meet Important ​

FieldMeaningWhat to do with it
Filter: / Rows Removed by Filter:Condition applied after reading the rowLarge removals on few results: index or predicate problem
Index Cond:Condition used to search the indexAbsent where you expected it: function or type mismatch
Recheck Cond: / Heap Blocks: exact= lossy=Bitmap recheck; lossy pagesLossy: raise work_mem
Heap Fetches:Index-only scan rows checked in the heapHigh: VACUUM to refresh the visibility map
Hash Cond: / Merge Cond: / Join Filter:Join keys / extra join conditionJoin Filter removing most rows: missing join key
Buckets: Batches: Memory Usage:Hash table size and spillsBatches > 1: spill
Sort Method: Sort Key: Presorted Key:Sort algorithm and keysexternal merge: spill
Workers Planned / LaunchedParallelism requested / obtainedLaunched < planned: worker pool exhausted
Subplans Removed: / never executedRun-time partition pruning / node skippedExpected
Cache Hits / Misses / EvictionsMemoize effectivenessMany misses: Memoize not helping
JIT:Compilation counts and timingJIT time dominates: raise jit_above_cost or disable
Planning Time / Execution TimeWhole-statement totalsExcludes 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.

text
     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';
sql
-- 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 ​

ProductHow to see the planPlanner notes
OracleEXPLAIN 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
SQLiteEXPLAIN QUERY PLAN (SCAN, SEARCH ... USING INDEX)Nested-loop joins only; join order by the Next-Generation Query Planner; ANALYZE fills sqlite_stat1/stat4
MongoDBdb.c.find(...).explain("executionStats"): winningPlan, rejectedPlans, totalKeysExamined, totalDocsExaminedCandidate plans race for a trial period; the winner is cached per query shape
CockroachDBEXPLAIN, EXPLAIN ANALYZE, EXPLAIN ANALYZE (DEBUG) bundleCost-based optimizer with automatic table statistics; plans are distributed across nodes
RedisNo query plannerCommands have documented complexity (O(1), O(log N)); "planning" is your data-structure choice

Mechanics ​

Every planner knob Must-know ​

Knob (PostgreSQL)DefaultScope you should useEffect
default_statistics_target100Per column via SET STATISTICSMCV/histogram size, sample size
random_page_cost / seq_page_cost4.0 / 1.0Server or tablespaceIndex vs seq scan balance
effective_cache_size4GBServerIndex scan attractiveness
work_mem4MBRole or SET LOCALPer sort/hash node memory
hash_mem_multiplier2.0ServerHash nodes get work_mem × this
join_collapse_limit / from_collapse_limit8 / 8SET LOCALHow far join order is searched
geqo_threshold / geqo12 / onServerWhen GEQO takes over
plan_cache_modeautoRole, database, SET LOCALGeneric vs custom plans
max_parallel_workers_per_gather2Role or SET LOCALWorkers per Gather
jit, jit_above_costoff (19), 100000RoleJIT 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_pruningonExperiments onlyPenalise a node type, not forbid it
temp_file_limit-1 (no limit)ServerCap temp files per process
log_temp_files-1Server (e.g. 0)Log every spill with its size
statement_timeout0Role or SET LOCALKills 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 ​

MessageCodeCauseFix
ERROR: canceling statement due to statement timeoutPostgreSQL 57014Bad plan ran past statement_timeoutFix the estimate; keep the timeout
ERROR: temporary file size exceeds temp_file_limit (…kB)PostgreSQL 53400Spill larger than the capBetter plan or SET LOCAL work_mem
ERROR: out of memory / OOM killerPostgreSQL 53200Many nodes × work_mem × sessionsLower global work_mem, pool connections
ERROR: EXPLAIN options ANALYZE and GENERIC_PLAN cannot be used togetherPostgreSQL 22023 (invalid parameter value)Mixed optionsUse one or the other
Query execution was interrupted, maximum statement execution time exceededMySQL 3024MAX_EXECUTION_TIME / max_execution_timeFix plan or raise the limit for that query
Out of sort memory, consider increasing server sort buffer sizeMySQL 1038sort_buffer_size too small for one rowRaise per session
Operator used tempdb to spill data (plan warning)SQL ServerMemory 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.

sql
-- 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:

go
// 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."

sql
-- 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 ​

ProblemSolutionHowAdvantageCost / limitation
Stale statistics after loadANALYZE in the jobLast step of every load/backfillCheap (sample), fixes many plans at onceLocks nothing heavy; sample variance
Correlated columnsCREATE STATISTICS(dependencies, mcv) on the pairFixes estimate at the sourceOnly equality/IN for dependencies; one more ANALYZE cost
Function on columnExpression statistics or indexON (lower(email))Planner gets a distributionIndex costs writes; statistics alone do not speed the scan
Nested-loop disasterFix outer estimateStats, predicate rewritePlan adapts to data changesNeeds diagnosis
Same, emergencyPin a planSET LOCAL enable_nestloop = off, pg_hint_plan, pg_plan_adviceImmediateFreezes; review when data changes
Sort/hash spillScoped memorySET LOCAL work_memNo global OOM riskPer transaction code change
Generic plan regressionCustom plansplan_cache_mode = force_custom_plan for role/txPlan per valuePlanning cost each call
CTE fenceNOT MATERIALIZEDLet filters push downUses indexesRe-evaluated if referenced twice
Planning too slowFewer joins / prepared statementsSplit query, join_collapse_limitBounded planning timePossibly worse plan
Huge IN listArray parameter= ANY($1)One parameter, stable text in pg_stat_statementsSame estimate quality

Stale statistics after a bulk load ​

sql
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.

go
// 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.

php
// app/Jobs/ImportOrders.php (handle method)
DB::table('orders')->insertUsing($columns, $stagingQuery);
DB::statement('ANALYZE orders');

Correlated columns ​

sql
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.

go
// 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()
}
go
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)
	}
}
php
// 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 ​

sql
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:

php
$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 ​

sql
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 ​

sql
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
<?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
<?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 ​

SituationFirst moveSecond moveAvoidWhy
Slow query after deploy, no data changeCompare plans before/after (auto_explain logs)Check SETTINGS, new predicatesAdding indexes blindlyUsually a query-shape change
Slow query after data loadANALYZERaise statistics target on skewed columnsHintsEstimates are stale
Estimate wrong on AND of two columnsCREATE STATISTICSComposite index if also selectiveenable_* flagsIndependence assumption
Estimate wrong on expressionExpression statistics/indexRewrite predicate to bare columnCasting in appNo distribution for the function
Spill to diskSET LOCAL work_memReduce rows earlier (filter, pre-aggregate)Global work_mem raiseMemory multiplies per node and session
Fast in psql, slow in appEXPLAIN EXECUTE / GENERIC_PLANplan_cache_mode per roleDisabling prepared statements globallyGeneric plan
15-table reportRead model / materialized viewjoin_collapse_limit + written orderGEQO tuningSearch space
OLTP query with JIT timejit = off for roleFix the estimateLeaving JIT on globallyCompilation overhead
MySQL bad join orderHistograms + ANALYZE TABLEJOIN_ORDER hintSTRAIGHT_JOIN everywhereEstimates first
SQL Server sniffingOPTION (RECOMPILE) on that statementPSP (compat 160), Query Store forcingClearing the whole plan cachePer-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× ​

LoadWhat breaks in planningChange
1×Nothing visible; estimates loose but tables smallpg_stat_statements, auto_explain sampled, ANALYZE in loads
10×Nested loops on misestimates, spills, generic-plan regressions, out-of-range timestampsExtended 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-analyzePartitioning 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):

sql
-- 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);
  1. Before and after ANALYZE.
sql
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';
  1. Correlated columns, then CREATE STATISTICS.
sql
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)
  1. Join algorithms side by side.
sql
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;
  1. Watch a hash join spill.
sql
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;
  1. Generic vs custom plan switch.
sql
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;
  1. CTE folding and the sort spill (bonus).
sql
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;
  1. MySQL comparison (optional).
sql
-- 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\G

Common misconceptions ​

BeliefReality
Cost is in millisecondsCost is in units of a sequential page read; compare only between plans of one query
A Seq Scan means a missing indexFor a large fraction of rows it is the cheapest plan; check the estimate
EXPLAIN ANALYZE updates statisticsIt executes the statement; ANALYZE (the command) updates statistics
EXPLAIN ANALYZE is read-onlyIt runs INSERT/UPDATE/DELETE for real; wrap in BEGIN … ROLLBACK
Nested loops are always badWith a small outer side and an index they are the fastest join and return rows first
CREATE STATISTICS takes effect immediatelyIt registers interest; ANALYZE collects
A CTE is always an optimisation fenceOnly before PostgreSQL 12, or with MATERIALIZED, or when referenced twice
Raising work_mem globally is safeIt is per node, per worker, per session; memory multiplies
actual rows is the totalIt is per loop; multiply by loops
Hints are the normal tuning toolThey freeze yesterday's plan; fix estimates first
Fast in psql means fast in the appThe app may run a generic plan through a prepared statement
More parallel workers is always fasterWorkers cost setup; many groups or small tables lose; workers may not launch
JIT always helpsIt costs compile time; harmful on short queries with inflated estimates
MySQL rows is rows returnedIt is estimated rows examined per lookup; see filtered

Cheat sheet ​

TopicRemember
First commandEXPLAIN (ANALYZE, BUFFERS, SETTINGS); writes inside BEGIN … ROLLBACK
Where to lookLowest node with estimated vs actual rows off by 10×
Per-loopactual rows and time are per loop; × loops for totals
Buffershit = cache, read = OS/disk, dirtied/written = changes/evictions, temp = spills
StatisticsANALYZE after loads; pg_stats: null_frac, n_distinct, MCV, histogram, correlation
Correlated columnsCREATE STATISTICS (dependencies, mcv) then ANALYZE
FunctionsExpression statistics or expression index; otherwise 0.5% guess
JoinsNested loop: small outer + index; hash: big equality, work_mem × 2; merge: sorted inputs
SpillsBatches > 1, external merge, temp written; fix with SET LOCAL work_mem
Join searchjoin_collapse_limit/from_collapse_limit 8, GEQO at 12
Prepared statements5 custom then maybe generic; plan_cache_mode; EXPLAIN (GENERIC_PLAN)
Productionpg_stat_statements to rank, auto_explain to capture, log_temp_files to see spills
MySQLEXPLAIN FORMAT=TREE, EXPLAIN ANALYZE, hash join since 8.0.18, /*+ */ hints, histograms, optimizer_trace
SQL ServerActual plan / SET STATISTICS XML; sniffing → OPTION (RECOMPILE), PSP, Query Store
StabilityStatistics first; pg_hint_plan Rows / pg_plan_advice last

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Planner / optimizerComponent that chooses the execution plan from candidate paths by estimated cost
Parse / rewriteStages that build the parse tree and expand views and rules before planning
PathCut-down plan representation the PostgreSQL planner costs and compares
Plan treeTree of physical operators the executor runs
Volcano / iterator modelEach operator implements next(); parents pull rows from children
CostEstimated work in units of one sequential page read
seq_page_cost / random_page_costCost of a sequential / random page read (1.0 / 4.0)
cpu_tuple_cost / cpu_index_tuple_cost / cpu_operator_costCPU cost per row / index entry / operator (0.01 / 0.005 / 0.0025)
effective_cache_sizePlanner's assumption of available cache; allocates nothing
Start-up costCost before the first row is returned
SelectivityFraction of rows a condition keeps
Cardinality estimateEstimated number of rows a node returns
ANALYZECommand that samples a table and stores statistics
pg_statsView over pg_statistic with per-column statistics
null_fracFraction of NULLs in a column
n_distinctDistinct values; negative = fraction of rows
most_common_vals (MCV)Most frequent values with their frequencies
histogram_boundsEqual-population bucket boundaries over non-MCV values
correlationAgreement between physical row order and column order
default_statistics_targetDefault size of MCV list and histogram (100)
CREATE STATISTICSExtended statistics on column groups or expressions
ndistinct / dependencies / mcv (extended)Group distinct counts / functional dependencies / multi-column MCV
Seq ScanFull table read in physical order
Index ScanIndex traversal with heap fetch per row
Index Only ScanAnswer from index; heap checked only for not-all-visible pages
Heap FetchesRows an index-only scan still checked in the heap
Bitmap Index Scan / Bitmap Heap ScanCollect TIDs into a bitmap, then read heap pages in order
Lossy bitmapPage-level bitmap after exceeding work_mem; requires recheck
Nested LoopJoin that runs the inner plan once per outer row
MemoizeCache of inner results for repeated keys in a nested loop
Hash JoinJoin that builds a hash table from one input and probes it
BatchesPartitions of a hash join or aggregate; > 1 means spill
Merge JoinJoin of two inputs sorted on the key
work_memMemory per sort/hash node before spilling (4MB)
hash_mem_multiplierMultiplier on work_mem for hash nodes (2.0)
SpillWriting intermediate data to temp files
Incremental SortSort of groups of input already ordered on a key prefix
top-N heapsortBounded sort that keeps only LIMIT rows
HashAggregate / GroupAggregateGrouping by hash table / over sorted input
Partial / Finalize AggregateTwo-stage aggregation in parallel plans
Gather / Gather MergeNodes collecting rows from parallel workers (unordered / ordered)
max_parallel_workers_per_gatherWorkers per Gather node (2)
JITLLVM compilation of expressions and tuple deforming
jit_above_costEstimated cost threshold for JIT (100000)
join_collapse_limit / from_collapse_limitSize limits for flattening joins/subqueries into one search (8)
GEQOGenetic Query Optimizer, used at geqo_threshold (12) FROM items
Interesting orderSort order useful to a later operator (System R)
Generic plan / custom planPlan reusable for any parameter / planned for specific values
plan_cache_modeauto, force_custom_plan, force_generic_plan
Parameter sniffingSQL Server term: compiling a cached plan from the first parameter values
GENERIC_PLANEXPLAIN option that plans a $1 query generically
MATERIALIZED / NOT MATERIALIZEDForce a CTE to be computed separately / folded
Subquery unnestingRewriting IN/EXISTS subqueries into semi/anti-joins
Predicate pushdownMoving filters into subqueries, views and scans
Partition pruningSkipping partitions at plan or run time
EXPLAIN optionsANALYZE, BUFFERS, VERBOSE, SETTINGS, WAL, FORMAT JSON, GENERIC_PLAN, SERIALIZE, MEMORY
loopsNumber of times a node executed; actuals are per loop
shared hit / read / dirtied / writtenBuffer cache hits / reads from OS / pages modified / pages evicted
temp read / writtenTemp file blocks from spills
Rows Removed by FilterRows read and discarded by a non-index condition
auto_explainContrib module that logs plans of slow statements
pg_stat_statementsContrib module aggregating statistics per normalised query
pg_hint_planThird-party extension reading planner hints from comments
pg_plan_advicePostgreSQL 19 contrib module to capture and reapply plan advice
enable_* flagsPlanner switches that penalise a node type, for experiments
MySQL EXPLAIN FORMAT=TREE / EXPLAIN ANALYZEIterator tree / executed tree with actual time, rows, loops
MySQL optimizer hints/*+ JOIN_ORDER(...) INDEX(...) BNL(...) SET_VAR(...) */ comments
MySQL histogramColumn statistics via ANALYZE TABLE … UPDATE HISTOGRAM (singleton, equi-height)
optimizer_traceMySQL JSON trace of the optimizer's decisions
join_buffer_sizeMySQL 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 optimizationSQL Server 2022 feature caching several plans per statement

References ​

Built by Morteza Negahi