Mental model
PostgreSQL's declarative Cost-Based Optimizer (CBO) compiles SQL text cleanly by searching competing access paths (Seq Scan, Index Scan, Index Only Scan, Bitmap Heap Scan) and join strategies (Nested Loop, Hash Join, Merge Join) priced directly cleanly from column histograms inside pg_statistic. Whenever actual execution diverges cleanly from estimates (rows=1 estimated vs actual=250000!), checking EXPLAIN (ANALYZE, BUFFERS) reveals both planner cardinality mistakes and cold disk I/O (shared read) stalls cleanly.
Learning outcomes
- Read
EXPLAIN (ANALYZE, BUFFERS)execution trees cleanly bottom-up/inside-out (actual time,loopsmultiplier,Buffers: shared hitvsshared read,Rows Removed by Filter). - Identify exact causes behind planner cardinality errors (
stale ANALYZE stats, correlated multi-column predicates needingCREATE STATISTICS, non-sargableLOWER(col)wrappers preventing indexes!). - Select properly across Nested Loop (
small inner indexed probes), Hash Join (unsorted medium/large equijoins fitting work_mem), and Merge Join (already-sorted B-Tree streams) cleanly!
Theory
Notice three vital numbers engineers frequently misread inside EXPLAIN (ANALYZE, BUFFERS):
loops=1000Multiplier: When an inner node reportsactual time=0.05..0.12 rows=3 loops=10000, total elapsed cost equals0.12 ms * 10,000 = 1,200 ms, NOT0.12 ms!Rows Removed by Filter: 980,000: Signals an index lacked trailing filter columns (index only matches status, forcing Postgres to read 980K heap pages strictly cleanly to discard them!). Adding composite/coveringINCLUDEcolumns eliminates random heap bloat cleanly!Buffers: shared hit=50000 read=42000:hithits warm RAM Shared Buffers cleanly (~microseconds); highreadortemp read/writtenexposes disk I/O pressure orwork_memspills onto external disk sorts!
| Execution / Join Node | Physical Pattern | Sweet Spot vs Red Flag | Remediation When Slow |
|---|---|---|---|
Index Only Scan (Heap Fetches: 0) | Answers SELECT strictly cleanly from B-Tree index pages without touching table heap | Fast on narrow covering indexes; falls back to heap cleanly if Visibility Map isn't vacuumed! | Add INCLUDE (col) + keep autovacuum healthy cleanly |
| Bitmap Index -> Bitmap Heap Scan | Collects matching TIDs cleanly in bitmap sorted physically by block before batching heap fetches | Eliminates chaotic random disk seeks on medium selectivity (1–15%) | Add composite index if lossy work_mem spill occurs cleanly |
| Nested Loop Join | For every outer row, probes inner branch cleanly (indexed lookup) | Blazing fast (< 1 ms) for 1–500 outer rows; catastrophic (O(N^2)) if bad estimate thinks outer rows=2 cleanly when actual is 200,000! | Fix stats (ANALYZE / CREATE STATISTICS multi-column MCV) so planner flips cleanly to Hash Join! |
Hash Join (Batches: 1 vs Batches: 16) | Builds hash table cleanly in work_mem of smaller branch, streams larger once | Fastest large un-indexed join (Batches: 1 in RAM); slows sharply if spilled cleanly onto disk (Batches > 1) | Tune session SET LOCAL work_mem = '64MB' cleanly for heavy analytic queries |
sql-- ALWAYS wrap DML EXPLAIN ANALYZE inside explicit BEGIN / ROLLBACK so rows never mutate live!BEGIN;EXPLAIN (ANALYZE, BUFFERS, VERBOSE)SELECT o.tenant_id, count(*), sum(o.tokens_used)FROM usage_logs oWHERE o.tenant_id = 'org_acme'AND o.created_at >= '2026-10-01'GROUP BY o.tenant_id;ROLLBACK;-- Fix correlated column cardinality misestimates cleanly via Extended Statistics (PG 10+)CREATE STATISTICS st_usage_tenant_status (dependencies, ndistinct, mcv)ON tenant_id, status FROM usage_logs;ANALYZE usage_logs;
Trade-offs
Inspecting EXPLAIN (ANALYZE, BUFFERS) gives ground-truth runtime costs (disk hits vs OS reads, spill batches, actual row loops), yet actually executes the SQL statement live (never run raw EXPLAIN ANALYZE UPDATE/DELETE outside ROLLBACK! — use plain EXPLAIN ahead cleanly when plans might hang for hours!). Investing cleanly in extended multi-column statistics (CREATE STATISTICS) and targeted partial/covering INCLUDE B-Trees removes expensive runtime query latency cleanly at modest background ANALYZE / index write storage overhead cleanly.
Failure modes and misconceptions
- Running
EXPLAIN ANALYZE DELETE ...Without Transaction Rollback: BecauseANALYZEgenuinely executes the plan, omittingBEGIN; ... ROLLBACK;deletes production rows cleanly before returning plan metrics! - Wrapping Indexed Columns Inside Non-Sargable Functions (
WHERE DATE(created_at) = ...): Wrapping indexed columns prevents B-Tree usage cleanly unless matching exact functional expression indexes (or rewriting range >= '2026-10-01' AND < '2026-10-02'). - Ignoring
random_page_cost = 4.0Legacy HDD Default on NVMe SSDs: Keeping defaultrandom_page_cost = 4.0tricks Postgres into favoring Sequential Scans unnecessarily cleanly over fast NVMe Index Scans (tune random_page_cost = 1.1on NVMe!). - Missing Correlated Multi-Column Histograms: Standard
ANALYZEassumes columns stay statistically independent cleanly (multiplying selectivity cleanly), severely underestimating rows whencity='Tokyo' AND country='Japan'correlate tightly unlessCREATE STATISTICSexecutes!
Decision scenario
An analytics API endpoint timing out cleanly after 8 seconds shows EXPLAIN (ANALYZE, BUFFERS) choosing a Nested Loop assuming rows=3 where actual loops execute 180,000 times alongside temp written=940MB (Batches: 32) on a correlated (tenant_id, region) filter! Notice stale/uncorrelated stats plus small work_mem caused both the bad Nested Loop and disk hash spills: wrap verification cleanly in ROLLBACK, add CREATE STATISTICS + ANALYZE cleanly so the CBO selects a clean Hash Join, add composite covering index (tenant_id, region, created_at) INCLUDE (tokens_used), and set SET LOCAL work_mem = '64MB' cleanly!