Query Execution: Compilation, Vectorization, Cubes

The problem with the naive approach

A row-by-row interpreter, for each row: check the query structure, perform comparisons on the needed columns, copy results to output. The per-row interpretation overhead dominates once you're scanning millions of rows.

Solution 1 — Query compilation

SELECT SUM(amount) FROM sales
WHERE date='2026-04-10' AND product='Widget'

↓ generate code

for each row in sales {
  if (row.date == '2026-04-10' &&
      row.product == 'Widget') {
    sum += row.amount
  }
}

↓ JIT compile (LLVM) → machine code
↓ run on loaded column data

Code is specific to this query, JIT-compiled to x86/ARM. No interpretation overhead, tight loops. Used by HyPer/Umbra, SingleStore, and Spark's whole-stage codegen; PostgreSQL JIT-compiles expressions with LLVM.

Solution 2 — Vectorized processing

Query: product='Widget' AND store='Store5'

Step 1 — equality on the product column
  in:  [Widget, Gadget, Widget, Gizmo, Widget]
  out: [1, 0, 1, 0, 1]        ← bitmap

Step 2 — equality on the store column
  in:  [Store5, Store1, Store5, Store2, Store3]
  out: [1, 0, 1, 0, 0]        ← bitmap

Step 3 — bitwise AND
  → [1, 0, 1, 0, 0]  → rows 1 and 3 match

Processes a batch of column values at a time, through a fixed set of predefined operators. Output is bitmaps, aggregates or filtered columns. Used by DuckDB, ClickHouse, Velox, Snowflake, BigQuery.

AspectCompilationVectorization
ApproachGenerate code, compile to machine codeInterpret, but process batches
Compilation stepJIT-compile the entire queryNone
Per-row overheadMinimal (tight loop)Minimal (SIMD on batches)
FlexibilityAny queryFixed operator set
Memory usageLower — no intermediate bitmapsHigher — stores bitmaps
CPU cacheSingle loop, hot cacheBatch operations, good locality
SIMD usageManual, in the generated codeAutomatic, via vector instructions

What both are exploiting

  • Sequential memory access — columnar storage means the data for one column is contiguous, which minimizes cache misses versus random access.
  • Tight inner loops — few instructions, no function calls; keeps the CPU pipeline busy and avoids branch mispredictions.
  • CPU parallelism — multiple threads across a query, plus SIMD within a thread: [1,2,3,4] + [1,1,1,1] = [2,3,4,5] in one instruction.
  • Operating directly on compressed data — process RLE- or dictionary-encoded columns without decompressing to a separate representation. Saves both memory and CPU.

Materialized views

✗ Virtual view — no storage

CREATE VIEW sales_summary AS
  SELECT date, product, SUM(amount)
  FROM sales GROUP BY date, product

When queried: executes the underlying
query on the fly, every time.

✓ Materialized view — stored results

CREATE MATERIALIZED VIEW sales_summary AS
  SELECT date, product, SUM(amount)
  FROM sales GROUP BY date, product

When queried: reads precomputed results.
Cost: must be updated when the underlying
data changes — and may be stale meanwhile.

A table-like object holding precomputed query results written to disk. Fast reads, slower writes, staleness. Best for repeated queries where some latency in freshness is acceptable.

Data cubes (OLAP cubes)

A multidimensional grid of precomputed aggregates.

Dimensions: Date × Product        Aggregate: SUM(amount)

           Widget  Gadget  Gizmo   Total
2026-04-09  $100    $200    $50    $350
2026-04-10  $150    $300    $75    $525
2026-04-11  $200    $250    $100   $550
Total       $450    $750    $225   $1425

"Total sales for Widget?"      → Widget column   = $450   (instant, no scanning)
"Total sales on 2026-04-10?"   → that row        = $525   (instant)

Real warehouses use many dimensions — Date × Product × Store × Promotion × Customer — where each cell holds the aggregate for that specific combination, and queries can summarize along any dimension by collapsing the others.

✓ Advantages

✓ Certain queries extremely fast (precomputed)
✓ No scanning millions of rows
✓ Great for standard reports
  (sales by region, by product, ...)

✗ Disadvantages

✗ Inflexible — limited to the cube's dimensions
✗ Can't ask "sales of items > $100"
  if price isn't a dimension
✗ Storage = product of all dimension cardinalities
✗ Update complexity — recalculating on data change

the same question, two ways

Raw data (flexible but slow):
  SELECT SUM(amount) FROM sales
  WHERE date='2026-04-10' AND product='Widget' AND store='Store5'
    AND promotion='Holiday' AND customer_segment='Premium'
  → scan billions of rows, filter on 5 dimensions → seconds to minutes

Data cube (fast but limited):
  cube[2026-04-10][Widget][*][*][*].sum()        → milliseconds

  But: "what proportion of sales come from items > $100?"
       price isn't a dimension → cannot answer from the cube at all
       → fall back to raw data, defeating the purpose

Warehouses use both. Raw data for flexibility (any query is possible), cubes as a performance boost for the common ones. Never cubes alone — they lack the flexibility that makes a warehouse a warehouse.

ConceptPurposeTrade-off
Query compilationFast execution via JIT machine codeComplex implementation
Vectorized processingFast execution via batched SIMD operationsHigher memory (bitmaps), fixed operator set
Materialized viewsPrecomputed query resultsMust be updated on data change; staleness
Data cubesPrecomputed multidimensional aggregatesLimited to the cube's dimensions

The Invariants

  • Guarantees: Both execution strategies remove per-row interpretation overhead, and precomputation makes a known, bounded set of queries answerable in constant time.
  • Does not guarantee: Freshness or generality. A materialized view can be stale; a cube simply cannot answer a question about a dimension it doesn't contain, at any price.