FullStack AI Hub
Studio
DB & Data Pipelines · 01. Storage & Execution
9 min
6 steps
Intermediate

Query Planner, Joins & Columnar Scans

Read EXPLAIN plans like an internals engineer: cardinality estimates, Nested Loop vs Hash Joins, and Parquet columnar pruning.

DB & Data Pipelines01. Storage & ExecutionLesson 2 of 2
9 minIntermediate6 steps

Query Planner, Joins & Columnar Scans

Read EXPLAIN plans like an internals engineer: cardinality estimates, Nested Loop vs Hash Joins, and Parquet columnar pruning.

Query Time
14.2 s
Row Est. Error
25,000×
CPU Burn
99%
Pages Read
1.8M
500k probesBI QueriesStalePlannerNested LoopRow Heap Disk
SQL Query / Plan
Full Table Scan / Spill
Hash Build / Column Read
Aggregated Result
Bad Plan / Disk Spill
In This LessonStep 1 of 6
What You Will Master
  • ✓Understand how cost-based optimizers use table histograms and cardinality statistics
  • ✓Choose between Nested Loop, Hash Join, and Sort-Merge Join based on selectivity and RAM
  • ✓Explain why columnar formats (Parquet/ClickHouse) beat row stores 50× on analytical aggregations
  • ✓Skip 95% of disk reads using partition pruning, min/max zone maps, and vectorized SIMD

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Nested Loop JoinJoining 10 selective indexed rows against a huge table (OLTP)Turns catastrophic O(N×M) if planner underestimates outer row count
Hash JoinJoining two large unindexed sets when the smaller side fits in `work_mem`Spills slow temp files to disk if hash table overflows RAM
Row-Oriented StorePoint lookups and inserting/updating complete user recordsReads all 40 unused columns just to `SUM(revenue)`
Columnar + Zone MapsBI dashboards aggregating millions of rows across 2–3 columnsSlow for single-row random updates; designed for batch/append writes

Step-by-Step Architectural Breakdown (6 Steps)

Full architectural walkthrough transcript and state transitions for Query Planner, Joins & Columnar Scans.

STEP 01 · PROBLEMJump to step →

Stale Statistics & The Catastrophic Nested Loop

After a bulk load of 500,000 orders, stale table statistics tell the planner the table still has 20 rows. The optimizer picks a **Nested Loop Join** instead of a Hash Join—turning a 40 ms query into a 14-second CPU fire.

watch:Whenever `EXPLAIN ANALYZE` shows a 100× gap between `estimated rows` and `actual rows`, stale statistics are steering the planner wrong.

Cost-Based OptimizerCardinality EstimateNested Loop TrapEXPLAIN ANALYZE
STEP 02 · SOLUTIONJump to step →

Fresh `ANALYZE` Stats & In-Memory Hash Join

Running `ANALYZE` refreshes column histograms. Seeing 500k rows, the planner switches to a **Hash Join**: build one in-memory hash table on the smaller dimension table and stream the larger orders table in a single O(N+M) pass.

good:Size `work_mem` carefully so Hash Joins stay in RAM instead of spilling slow temp batches to disk.

ANALYZE HistogramsHash Joinwork_memLinear Scan O(N+M)
STEP 03 · TECHNIQUEJump to step →

Columnar Storage & Projection Pushdown

To compute `SELECT SUM(amount) FROM events` across 50M rows with 40 columns, a row store reads all 40 columns from disk. A **Columnar Store (Parquet/ClickHouse)** reads *only* the compressed `amount` column—cutting disk I/O 30× and enabling SIMD vectorized math.

idea:Grouping identical data types inside one column unlocks dictionary and run-length encoding—often achieving 8×–12× compression.

Columnar StorageParquetProjection PushdownSIMD Vectorization
STEP 04 · TECHNIQUEJump to step →

Partition Pruning & Min/Max Zone Maps

Every Parquet row group stores tiny header metadata (`min_date`, `max_date`, `min_tenant_id`, `max_tenant_id`). Filtering by `date = 2026-11-30` skips 98% of row groups without ever downloading them from S3.

good:Sorting data by `(tenant_id, event_date)` before writing Parquet makes min/max zone maps razor-sharp.

Zone MapsRow Group SkippingPartition PruningClustering Key
STEP 05 · TRADE-OFFJump to step →

Why OLTP and OLAP Need Separate Engines

Row stores excel at 10,000 point updates/sec; columnar engines excel at scanning 100M rows. Running heavy BI joins directly against your primary Postgres burns buffer-pool cache and stalls checkout—split OLTP and OLAP workloads cleanly.

watch:One unindexed `GROUP BY` on your primary OLTP instance can evict the entire hot user table from the buffer pool.

Workload IsolationOLTP vs OLAPBuffer Pool PollutionHTAP Trade-Off
STEP 06 · RECAPJump to step →

Query Execution & Columnar Recap

Keep OLTP fast with accurate `ANALYZE` statistics and selective indexes, and run analytical aggregations on sorted columnar Parquet tables powered by zone-map skipping and SIMD execution.

good:Always read `EXPLAIN (ANALYZE, BUFFERS)`—it reveals exact disk pages read, row estimate accuracy, and memory spills.

EXPLAIN BUFFERSHash JoinParquetZone Maps

Related Production Deep-Dives & Simulators

Related Systems Course
Free · Verifiable Credential

FS-401RAG Engineer

Build evidence-carrying retrieval systems from ingestion and provenance through search reranking grounded generation and evaluation.

21 concepts~25h 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.