FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Query Optimization & EXPLAIN ANALYZE

Cost-based query planner, EXPLAIN ANALYZE output reading, sequential scans vs index scans, and join strategies.

Freshness: current•16 min read•Data Engineering and Databases

Key Learning Outcomes

  • ✓Analyze query execution plans with EXPLAIN ANALYZE
  • ✓Eliminate sequential scan bottlenecks on large tables
Full Technical Reference Document

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.

Parse SQL -> Rewrite -> CBO planner
Query pg_statistic histograms & MCVs
Compare Seq vs Index vs Bitmap & Join costs
Run query safely inside ANALYZE, BUFFERS
Spot row misestimates & shared read disk spikes
Conceptual teaching model synthesized from:PostgreSQL 16 Architecture, MVCC & Query Optimization ManualDesigning Data-Intensive Applications: Replication, Transactions and Distributed State

Learning outcomes

  • Read EXPLAIN (ANALYZE, BUFFERS) execution trees cleanly bottom-up/inside-out (actual time, loops multiplier, Buffers: shared hit vs shared read, Rows Removed by Filter).
  • Identify exact causes behind planner cardinality errors (stale ANALYZE stats, correlated multi-column predicates needing CREATE STATISTICS, non-sargable LOWER(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):

  1. loops=1000 Multiplier: When an inner node reports actual time=0.05..0.12 rows=3 loops=10000, total elapsed cost equals 0.12 ms * 10,000 = 1,200 ms, NOT 0.12 ms!
  2. 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/covering INCLUDE columns eliminates random heap bloat cleanly!
  3. Buffers: shared hit=50000 read=42000: hit hits warm RAM Shared Buffers cleanly (~microseconds); high read or temp read/written exposes disk I/O pressure or work_mem spills onto external disk sorts!
Execution / Join NodePhysical PatternSweet Spot vs Red FlagRemediation When Slow
Index Only Scan (Heap Fetches: 0)Answers SELECT strictly cleanly from B-Tree index pages without touching table heapFast 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 ScanCollects matching TIDs cleanly in bitmap sorted physically by block before batching heap fetchesEliminates chaotic random disk seeks on medium selectivity (1–15%)Add composite index if lossy work_mem spill occurs cleanly
Nested Loop JoinFor 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 onceFastest 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 o
WHERE 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: Because ANALYZE genuinely executes the plan, omitting BEGIN; ... 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.0 Legacy HDD Default on NVMe SSDs: Keeping default random_page_cost = 4.0 tricks Postgres into favoring Sequential Scans unnecessarily cleanly over fast NVMe Index Scans (tune random_page_cost = 1.1 on NVMe!).
  • Missing Correlated Multi-Column Histograms: Standard ANALYZE assumes columns stay statistically independent cleanly (multiplying selectivity cleanly), severely underestimating rows when city='Tokyo' AND country='Japan' correlate tightly unless CREATE STATISTICS executes!

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!

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next