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.
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.
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):
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;| lpint2 | lp_lenint2 | order_idint4 | line_noint2 | product_idint4 | qtyint4 | unit_pricenumeric |
|---|---|---|---|---|---|---|
| 1 | 47 | 2 | 1 | 125 | 1 | 141.43 |
| 2 | 47 | 2 | 2 | 149 | 1 | 142.69 |
| 3 | 47 | 3 | 1 | 187 | 2 | 49.70 |
| 4 | 47 | 3 | 2 | 116 | 2 | 166.22 |
| 5 | 45 | 3 | 3 | 1 | 2 | 49.00 |
| 6 | 47 | 4 | 1 | 47 | 1 | 3.59 |
| 7 | 47 | 4 | 2 | 95 | 1 | 169.46 |
| 8 | 47 | 4 | 3 | 2 | 1 | 39.50 |
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:
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;| relnamename | relpagesint4 | sizetext |
|---|---|---|
| narrow | 448 | 3584 kB |
| wide | 1472 | 12 MB |
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:
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;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:
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:
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;| valuesint8 | distinct_valuesint8 | runs_in_id_orderint8 | runs_sortedint8 |
|---|---|---|---|
| 10000 | 6 | 869 | 6 |
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).
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
- 489 calls: 488 full vectors and one partial
- ├── next() → a vector of 2,048 c7 valuesone tight loop adds them, no per-row calls
- └── column scan of c7 onlyreads the c7 column, decompresses a block at a time
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.