skip to content

column stores and vectorized execution

the same table stored by column and run a batch at a time. duckdb's numbers next to postgres's.

address
everything.deep_dives.columnar_and_vectorized
part
part 18, deep dives and interviews
chapter
chapter 4 of 10
reading time
9 min

a row store keeps each row's columns together, which is perfect for "fetch order 42" and wasteful for "sum one column over a billion rows". a column store keeps each column together, so an aggregate reads only the columns it names, and a column of one type compresses well. vectorized execution is the matching engine: operators pass batches of a few thousand values instead of one row at a time.

postgres is a row store with a row-at-a-time executor. here's what that costs, measured, and what the other design does instead.

the picture

you know how an analytics query on a big postgres table, SELECT sum(amount) FROM orders, can take seconds even though "it's just adding numbers"? the adding is cheap. the problem is everything around it: postgres walks every page, every tuple header, every column you didn't ask for, and calls a function per row to hand each one up the plan.

think of a filing cabinet of customer folders (rows). to total everyone's balance, you open every folder, flip to the balance page, write it down, close the folder. a column store keeps one long ledger per field instead: the balances, all on one sheet, top to bottom. you read one sheet.

stored
query
bytes this query touches
406 B
of which the answer needs
32 B
rows
8

the heap keeps whole rows together, so summing one 4-byte column still drags every tuple through memory: headers, all 5 columns, and a line pointer each. 406 bytes touched for 32 bytes of answer.

tuple headerbytes the query readsbytes it skips
recorded: real lp_len from pageinspect, postgres 18.6 (PGlite 0.5.12), shop.order_items page 0. the column layout is the textbook model
eight real rows of order_items, stored both ways. the tuple lengths are pageinspect's lp_len from the run block below. switch the layout and the query: in the heap, SUM(qty) touches every byte of every tuple; in a column store it touches one strip.

here are those eight tuples, straight off page 0 (inside a tuple explains the bytes):

sqldb=shop · ext=pageinspect
SELECT lp, lp_len, i.order_id, i.line_no, i.product_id, i.qty, i.unit_price
FROM heap_page_items(get_raw_page('order_items', 0)) AS h
JOIN order_items AS i ON i.ctid = h.t_ctid
WHERE h.lp <= 8
ORDER BY h.lp;
output, from postgres 18.6
SELECT 8
lpint2lp_lenint2order_idint4line_noint2product_idint4qtyint4unit_pricenumeric
147211251141.43
247221491142.69
34731187249.70
447321162166.22
545331249.00
647414713.59
74742951169.46
847432139.50
(8 rows)

each is 45 or 47 bytes, and 24 of those are the tuple header (23 bytes, padded) that MVCC needs (transaction ids, xmin and xmax). the qty is 4.

what a row store pays for one column

make it bigger. a table with an id and 20 integer columns, and a second table holding only one of them:

sqlempty db · session wide
CREATE TABLE wide AS
SELECT g AS id,
       (g * 7) % 1000 AS c1,  (g * 8) % 1000 AS c2,  (g * 9) % 1000 AS c3,  (g * 10) % 1000 AS c4,
       (g * 11) % 1000 AS c5, (g * 12) % 1000 AS c6, (g * 13) % 1000 AS c7, (g * 14) % 1000 AS c8,
       (g * 15) % 1000 AS c9, (g * 16) % 1000 AS c10, (g * 17) % 1000 AS c11, (g * 18) % 1000 AS c12,
       (g * 19) % 1000 AS c13, (g * 20) % 1000 AS c14, (g * 21) % 1000 AS c15, (g * 22) % 1000 AS c16,
       (g * 23) % 1000 AS c17, (g * 24) % 1000 AS c18, (g * 25) % 1000 AS c19, (g * 26) % 1000 AS c20
FROM generate_series(1, 100000) AS g;
CREATE TABLE narrow AS SELECT c7 FROM wide;
VACUUM ANALYZE wide;
VACUUM ANALYZE narrow;
SELECT relname, relpages, pg_size_pretty(pg_relation_size(oid)) AS size
FROM pg_class WHERE relname IN ('wide', 'narrow') ORDER BY relname;
output, from postgres 18.6
#1 · SELECT 100000
#2 · SELECT 100000
#3 · VACUUM
#4 · VACUUM
#5 · SELECT 2
relnamenamerelpagesint4sizetext
narrow4483584 kB
wide147212 MB
(2 rows)

100,000 values of c7 are 400 KB of integers. as a one-column postgres table they take 3.5 MB, because every row still carries a header and a line pointer. summing c7 from the wide table reads every page of it:

sqlempty db · session wide
continues session wide (1 earlier block run first)
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT sum(c7) FROM wide;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT sum(c7) FROM narrow;
output, from postgres 18.6
#1 · EXPLAIN
Aggregate (actual rows=1.00 loops=1) Buffers: shared hit=1472 -> Seq Scan on wide (actual rows=100000.00 loops=1) Buffers: shared hit=1472 Planning: Buffers: shared hit=7 read=1
#2 · EXPLAIN
Aggregate (actual rows=1.00 loops=1) Buffers: shared hit=448 -> Seq Scan on narrow (actual rows=100000.00 loops=1) Buffers: shared hit=448 Planning: Buffers: shared hit=5

shared hit is pages read from the buffer pool (EXPLAIN ANALYZE and BUFFERS): 1,472 pages for the wide table, 448 for the narrow one: more than three times the pages for the same answer. on disk, that's three times the I/O. now the same thing at a million rows on a real server, timed:

count(*), wide41.1 ms
sum(c7), narrow42.4 ms
sum(c7), wide46.9 ms
10 sums, wide70.5 ms
measured on this mac (m4 pro), postgres 18.6 (Postgres.app), 1,000,000 rows, warm cache, median of 9 runs, no parallel workers, jit off
execution time on a native postgres 18.6, everything already in shared buffers. the wide table is 112 MB (14,286 pages), the one-column table 35 MB (4,480 pages), and the integers themselves would be 4 MB.

this is the interesting part. with everything cached, reading three times the pages cost only about 10% more (46.9 ms vs 42.4 ms), and even count(*), which adds nothing up, took 41.1 ms. so the time isn't going into bytes. it's going into rows: a million trips through the scan, the visibility check, the tuple deforming, and an aggregate transition call, one row at a time. that's about 40 ns of machinery per row before any arithmetic. a column store attacks both halves of this: fewer bytes (one column, compressed) and fewer trips (a batch at a time).

columns compress

a column holds one type, often with few distinct values, often sorted or nearly so. that's what compression wants. orders.status has six possible values; sorted, the whole column is a handful of runs:

sqldb=shop
WITH o AS (
  SELECT status,
         lag(status) OVER (ORDER BY id) AS prev_by_id,
         lag(status) OVER (ORDER BY status, id) AS prev_sorted
  FROM orders
)
SELECT count(*) AS "values",
       count(DISTINCT status) AS distinct_values,
       count(*) FILTER (WHERE status IS DISTINCT FROM prev_by_id) AS runs_in_id_order,
       count(*) FILTER (WHERE status IS DISTINCT FROM prev_sorted) AS runs_sorted
FROM o;
output, from postgres 18.6
SELECT 1
valuesint8distinct_valuesint8runs_in_id_orderint8runs_sortedint8
1000068696
(1 row)

10,000 values. stored by run-length encoding (value, count), the sorted column is six pairs; in id order it would be 869. either way, a dictionary turns each status into a 3-bit code, since six values fit in three bits. postgres can't do either for a column: it compresses large individual values (TOAST), never a column across rows, because the rows aren't stored by column. duckdb's documentation on its vector format says dictionary-compressed columns can even stay compressed while the query runs, as an index into a small dictionary (duckdb: vectors).

predict the output
which query is a column store slowest at, relative to postgres?
sql
SELECT sum(qty) FROM order_items;
SELECT * FROM order_items WHERE order_id = 42 AND line_no = 1;
SELECT status, count(*) FROM orders GROUP BY status;

a batch at a time

postgres's executor is the iterator model: every node has a next() that returns one row, and the aggregate at the top calls it until it runs out. a million rows, a million calls, each through a few layers of function pointers. Boncz, Zukowski and Nes's paper "MonetDB/X100: hyper-pipelining query execution" (CIDR 2005) argued that this per-tuple interpretation overhead, not I/O, dominates analytical queries on modern CPUs, and proposed handing vectors of values between operators instead, so each operator runs a tight loop over an array.

  • 1,000,001 calls to next() below it
  • ├── next() → one tuple slotdeform the tuple to get c7, then call int4_sum once
  • └── Seq Scan on wideevery page, every tuple: visibility check per tuple
drawn by hand · after the iterator model chapter, duckdb's vector docs and the X100 paper
the same SELECT sum(c7) FROM wide over 1,000,000 rows, as calls between two plan nodes. postgres's side is how its executor works; the vectorized side uses duckdb's default vector size of 2,048 values, from its documentation. the call counts are arithmetic, not measurements.

why vectors and not "all of it at once"? a vector small enough to stay in the CPU cache (duckdb's default STANDARD_VECTOR_SIZE is 2,048 tuples) gets the loop efficiency without materializing a whole column in memory. whole-column-at-a-time was the earlier MonetDB design, and X100 is named for what it changed.

postgres does have pieces of this idea. parallel query splits the scan across workers (turned off in the measurement above). JIT compilation (jit = on, used when a query's estimated cost is high enough) compiles expressions and tuple deforming to machine code, which cuts some of that per-row overhead without changing the row-at-a-time shape. neither makes the heap store columns.

keylines

  • row store: a row's columns together. great for one row, wasteful for one column of every row.
  • column store: one column together. reads only what the query names, and compresses well.
  • in postgres a one-int table is still mostly tuple headers and line pointers.
  • warm cache, postgres's cost is per row, not per byte: that's what vectorized execution attacks.
  • vectorized: next() returns a batch (duckdb: 2,048 values), not a row.