Columnar and analytics: ClickHouse, DuckDB, Parquet, the lakehouse
Why the same aggregate takes a second in Postgres and tens of milliseconds in a column store, and what the column store charges you for it
The shop's orders table has 2 million rows and six columns, and its Postgres heap is about 150 MB. You run SELECT sum(total_cents) FROM orders. total_cents is a 4-byte integer. Roughly how many bytes does a column store have to read to answer it?
Every database you have met so far in this course stores a row’s columns next to each other. That is the right layout for a shop: placing an order writes one row, showing an order reads one row, and both touch one or two 8 KB pages. It is the wrong layout for the question the finance team asks every morning: revenue by category by month, over every order ever placed.
This chapter puts the same shop rows into three engines (Postgres, DuckDB and ClickHouse) and measures why the analytical ones win aggregates by 10 to 50 times on a laptop and by more at scale. Then it covers what they charge for it, the file format they all share (Parquet), and what happens when you put that format on object storage and call it a table (the lakehouse).
Two layouts for the same table
You met the Postgres heap in the storage chapter. An orders tuple is a 24-byte header followed by its columns in order: id (8 bytes), customer_id (8), status (a short text, about 8 bytes with its length byte), total_cents (4, then 4 bytes of alignment padding), created_at (8) and shipped_at (8). That is about 72 bytes, plus a 4-byte line pointer: 76 bytes per row, about 107 rows per 8 KB page, and about 18,700 pages, or 150 MB, for 2 million orders. order_items is about 60 bytes per row and 360 MB for 6 million rows.
To sum total_cents, Postgres reads all 150 MB, whether from shared buffers, the OS page cache or disk. Four bytes out of every 76 are useful. The other 95% is moved through the CPU caches and thrown away.
A column store splits the same table vertically. Each column lives in its own file (ClickHouse), its own segment within a row group (DuckDB), or its own column chunk (Parquet). Rows are still identifiable, because the nth value of every column belongs to the nth row. The sum reads one file.
That one change is the headline, but on its own it explains a factor of 5 to 20, not the whole gap. Four more mechanisms stack on top of it.
Why aggregates get faster
Compression that works because a column is one type
A page of Postgres rows mixes integers, timestamps and text, so it compresses poorly, and Postgres does not compress heap pages at all (only large values through TOAST). A column is one type, often sorted or nearly sorted, and usually has far fewer distinct values than rows. Column stores pick an encoding per column, per block:
- Dictionary encoding.
statushas four values. Store each distinct string once and replace every value by a small integer: 2 bits instead of 8 bytes. ClickHouse calls thisLowCardinality(String); Parquet writes a dictionary page per column chunk. - Run-length encoding. If the column is sorted, 1.7 million
shippedvalues in a row become one pair: (shipped, 1,700,000). - Bit-packing and frame of reference.
qtyinorder_itemsis 1 to 4. Subtract the block minimum and store each value in 2 bits instead of 32. - Delta encoding.
idandcreated_atare monotone in the shop, so storing differences between neighbours turns 8-byte values into a few bits each.
A general-purpose compressor (LZ4 by default in ClickHouse, Snappy or Zstandard in Parquet) runs over the encoded result. In the lab, 2 million status values take about 0.3 MB in a Zstandard Parquet file: under 2 bits per row. Whole-table ratios of 3 to 10 times are typical for business data and 10 to 20 times for logs. Fewer bytes means less I/O and, more importantly once the data is in memory, less memory bandwidth, which is what an in-memory scan is limited by.
Vectorised execution
Postgres executes a plan the way the planner chapter showed: a tree of operators, each of which returns one row when its parent asks for the next. For a hash aggregate over 6 million rows that is 6 million calls through the scan, 6 million through the join, 6 million through the aggregate, each one an indirect function call, a tuple deform, and an expression evaluation for qty * unit_price_cents. When the real work per row is one multiply and one add, the interpretation overhead is most of the cost. Postgres’s JIT (on when a plan’s cost exceeds jit_above_cost, 100,000 by default) compiles the expressions and the tuple deforming, which helps by tens of percent, but the engine still moves one row at a time.
Column engines move vectors. MonetDB/X100 showed in 2005 that processing batches of around a thousand values per operator call keeps the batch in the CPU cache, amortises the call overhead across the batch, and turns the inner loop into a tight loop over an array that the compiler can unroll and turn into SIMD instructions. DuckDB’s vectors hold 2,048 values; ClickHouse processes blocks of tens of thousands of rows per column. The X100 paper measured TPC-H query 1, with the data already in memory, running one to two orders of magnitude faster than in row-at-a-time engines on the same hardware: the whole gain came from the CPU, none from I/O.
Skipping blocks that cannot match
Postgres skips data through B+ tree indexes, and a sequential scan reads everything (BRIN indexes are the exception, and they are the same idea as what follows). Column stores keep small summaries of every block instead:
- DuckDB splits a table into row groups of 122,880 rows and records the minimum and maximum of every column in each. A filter on
created_at >= '2026-01-01'skips every row group whose maximum is earlier. These summaries are called zone maps (or min-max indexes). - ClickHouse sorts each table by its
ORDER BYkey and keeps a sparse primary index: one entry for every granule of 8,192 rows (index_granularity). For 2 million orders that is 245 entries, which sits in memory, and a range filter on the key reads only the granules that can match. - Parquet stores min, max and null count for every column chunk in the footer, and optionally per page in a page index.
All three only work when the data is clustered on the filtered column. The shop’s created_at grows with id because orders were inserted in time order, so a date filter prunes well. A filter on customer_id, whose values are scattered through the table, prunes nothing: every block’s minimum is near 1 and its maximum near 500,000. Choosing the sort key is the single most important physical design decision in ClickHouse for exactly this reason.
Late materialisation
A row engine assembles each row early and carries it through the plan. A column engine evaluates the filter on the filter column alone, producing a list of matching positions, and fetches the other columns only for those positions, as late as possible. If a filter keeps 1% of rows, the other columns are read and decoded for 1% of rows.
Abadi, Madden and Hachem measured how much each of these mechanisms is worth by switching them off one at a time in C-Store. With all of them on, the average Star Schema Benchmark query took 4.0 s; with all of them off, 41.0 s. Late materialisation alone was worth a factor of about 3 and compression a factor of about 2. A column store without these is a row store with an awkward file layout, which is also why their attempts to emulate a column store inside a row store (one two-column table per column) did not come close.
What the numbers look like on the shop
These are the numbers to expect from the lab at scale 1 on a 2023-or-later laptop with the data warm in memory. Your absolute times will differ; the ratios are what to check.
| Postgres 17 | DuckDB | ClickHouse | |
|---|---|---|---|
orders + order_items on disk |
about 510 MB of heap, plus about 175 MB of primary keys | about 60 to 100 MB in one file | about 80 to 160 MB with the default LZ4 |
| Q1: 2026 orders by status (2 M rows) | 150 to 400 ms | 5 to 30 ms | 10 to 40 ms |
| Q2: revenue by category, 6 M-row join | 0.8 to 2.5 s | 20 to 100 ms | 40 to 150 ms |
Point read of one order by id |
under 0.2 ms (primary key) | 1 to 5 ms | 5 to 30 ms (id is not the sort key) |
| Insert one order | well under 1 ms | a few ms | several ms, and one new part |
So 10 to 50 times on the aggregates, not 100. The course plan promised 100, and you get it when the conditions are less kind to the row store: data read from disk instead of memory, tables with 50 or 100 columns (event and log tables usually are, and the column store’s advantage grows with every column the query does not touch), or billions of rows, where Postgres’s single machine and its two parallel workers per query (max_parallel_workers_per_gather defaults to 2) run out long before a ClickHouse cluster does. The last two rows of the table are the bill, and the next section is about paying it.
Where column stores hurt
Point reads and wide rows. Reading one order means one seek per column, and each seek decompresses a whole block (a ClickHouse granule of 8,192 rows, a DuckDB vector) to extract one value. SELECT * on a 100-column table does that 100 times. A column store serving a product page is the wrong tool even if it is fast enough at low load.
Small inserts. Column files are compressed and sorted, so nobody appends a row in place. ClickHouse writes every INSERT as a new immutable part (a directory with one compressed file and one marks file per column) and merges parts in the background, the same shape as the LSM trees chapter. One row per insert means one part per row. Past parts_to_delay_insert (1,000 active parts in a partition) the server deliberately slows inserts down, up to max_delay_to_insert (1 s) each; past parts_to_throw_insert (3,000) it refuses them with TOO_MANY_PARTS. The ClickHouse documentation asks for batches of at least 1,000 rows and ideally 10,000 to 100,000. If the clients cannot batch, async_insert = 1 makes the server buffer inserts and flush every 200 ms (async_insert_busy_timeout_ms), 100 MiB or 450 queries, whichever comes first. DuckDB has a different limit: one process at a time can open a database file for writing, so it is not a shared ingestion target at all.
Updates and deletes. Changing a value means rewriting the compressed block that holds it. In ClickHouse, ALTER TABLE ... UPDATE and ALTER TABLE ... DELETE are mutations: asynchronous jobs that rewrite every affected part, and on a large table they run for minutes and compete with merges. The lightweight DELETE FROM writes a hidden _row_exists mask instead and the rows are physically removed at the next merge of that part, so disk usage does not fall when the statement returns. The idiomatic pattern is not to update at all: insert a new version of the row into a ReplacingMergeTree, which keeps the latest version per sort key when parts merge, and accept that queries see duplicates until then unless they add FINAL, which costs query time.
High-cardinality GROUP BY. A hash aggregate holds one entry per group in memory. Grouping 6 million line items by 40 categories needs kilobytes; grouping a billion events by session id needs the whole set of session ids. DuckDB spills to disk when it passes its memory_limit (80% of RAM by default). ClickHouse fails the query with a memory-limit error unless you allow it to spill with max_bytes_before_external_group_by. Know which of your dashboards group by something unbounded.
Joins and transactions. Both engines join well enough for star schemas (a large fact table and small dimensions, which is Q2), but ClickHouse’s default hash join builds the right-hand table in memory, so the larger table goes on the left, and many ClickHouse users denormalise into one wide table to avoid joins entirely. Neither is an OLTP engine: ClickHouse has no multi-statement transactions, and DuckDB’s transactions are for one process.
DuckDB: analytics inside your process
DuckDB is to analytics what SQLite is to transactions: a library linked into your process, one file on disk, no server. It runs multithreaded on every core, spills to disk when a query outgrows memory, and reads Parquet, CSV and JSON files, S3 URLs, and other databases in place.
The postgres extension is the one that matters for this course. ATTACH 'host=... dbname=shop ...' AS pg (TYPE postgres, READ_ONLY) makes every Postgres table visible as pg.public.orders. DuckDB reads them with the binary COPY protocol, split into ranges of 1,000 heap pages by ctid (pg_pages_per_task) so several connections read in parallel, and runs the rest of the query in its own vectorised engine. Run against the live Postgres tables, a DuckDB aggregate is usually somewhat faster than Postgres running the same SQL, because the execution is vectorised, but it still drags every byte out of the row-store heap over a socket. Copy the table into DuckDB’s own storage once and the same query is 10 to 50 times faster. The storage layout is the bigger half of the win.
That makes DuckDB the cheapest analytics tier you can build: a scheduled job copies or exports the shop into Parquet, and analysts query the files from their laptops. It stops being enough when many users need the same data concurrently, when the data must be seconds fresh, or when it outgrows one machine’s disk.
ClickHouse: MergeTree
ClickHouse is a server built for many concurrent queries over continuously arriving data, and it scales out with sharding and replication. Nearly every table you create uses an engine from the MergeTree family, and three choices in the CREATE TABLE decide how it behaves.
ORDER BYis the sort order of every part and the sparse primary index. Put the columns you filter on most first, lower cardinality before higher:ORDER BY (status, created_at)lets a query for one status and a date range read a narrow slice. Unlike a Postgres primary key it does not enforce uniqueness.PARTITION BYsplits data into independent sets of parts, usually by month. It makes dropping old data instant (ALTER TABLE ... DROP PARTITION), and it is not an index: the parts limits above apply per partition, so partitioning by day with a year of data, or by customer, multiplies the part count and the merge work.- Column types and codecs.
LowCardinality(String)for anything with up to tens of thousands of distinct values, the narrowest integer that fits,DateTimerather than strings, and codecs such asDeltaorDoubleDeltafor monotone columns andZSTDwhere CPU is cheaper than disk.
Rollups come back as materialised views, but incremental ones: a view with an AggregatingMergeTree target updates a per-hour summary as each insert arrives, which is the Cloudflare pipeline’s cron jobs done by the database, on raw data that stays queryable.
Parquet: the file every engine reads
Parquet is the column store turned into a file format, and every engine in this chapter, plus Spark, Trino, Snowflake, BigQuery and pandas, reads it. A file is laid out like this:
- A 4-byte magic number,
PAR1. - One or more row groups, each a horizontal slice of the rows. Inside a row group, each column is stored contiguously as a column chunk, and each chunk is divided into pages (a dictionary page, if dictionary encoding is used, then data pages). Pages are the unit of encoding and compression.
- A footer: the schema, the byte offset and size of every column chunk, and statistics (min, max, null count) per chunk. Then the footer’s length and
PAR1again.
A reader fetches the last few kilobytes first, parses the footer, decides which row groups survive the filter and which columns the query needs, and issues one range read per needed column chunk. On S3 that means a 10 GB file can answer a narrow query with a handful of GET requests totalling a few MB. Nested data (lists, structs) is stored with the definition and repetition levels from Google’s Dremel paper, so a nested field is still a flat column.
Row group size is the knob. The format’s documentation recommends large row groups, 512 MB to 1 GB, for large sequential reads on HDFS; DuckDB writes 122,880 rows per row group by default (ROW_GROUP_SIZE in COPY). Too small and the footer grows, statistics get coarse in a different way, and a reader issues thousands of small requests. The classic data-lake failure is the related small files problem: a streaming job that writes one 50 KB file every few seconds produces millions of files, and listing and opening them costs more than reading them.
Parquet files are immutable. To change one row you rewrite the file. Which brings us to tables.
The lakehouse: tables made of files
A directory of Parquet files on S3 is cheap, durable and readable by every engine. It is not a table. A writer adding ten files is not atomic, so a reader that lists the directory halfway through sees six. Two writers can overwrite each other. Renaming a column means rewriting everything. Deleting one customer’s rows for a GDPR request means finding and rewriting every file that contains them. And listing a prefix with a million objects is slow.
Table formats fix this with a layer of metadata files next to the data files.
- Apache Iceberg keeps a tree: a table metadata file (schema, partition spec, list of snapshots) points to a manifest list per snapshot, which points to manifest files, which list data files with their partition values and column statistics. A commit writes new manifests and a new metadata file, then atomically swaps the catalog’s pointer from the old metadata file to the new one. Two writers race on that swap, one wins, and the other retries on top of it: optimistic concurrency control, the same idea as in the isolation chapter, at the granularity of a table.
- Delta Lake keeps an ordered log of JSON commit files in
_delta_log/,00000000000000000000.jsonupwards, and writes a Parquet checkpoint of the log every 10 commits by default so readers do not replay thousands of JSON files. Whoever writes the next numbered file first commits.
Both give readers snapshot isolation (a query reads one snapshot’s file list, whatever writers do meanwhile), time travel (read an older snapshot), schema evolution without rewrites, and row-level deletes, either by rewriting affected files (copy-on-write) or by writing small delete files that readers apply on the fly (merge-on-read). The lakehouse is this arrangement used as the warehouse: open files in your own bucket, a table format over them, and any engine you like on top, with storage and compute billed separately.
The costs move rather than disappear. Someone has to run compaction to merge small files, expire old snapshots so storage stops growing, and operate the catalog, which is now the single point every commit goes through. The warehousing chapter in module four covers building that platform; for the shop, the decision is usually smaller.
Putting it together for the shop
The shape that works at almost every size is the same: Postgres stays the system of record for orders and payments, and a copy of the data in columnar form answers analytical questions. What changes is how the copy is made and where it lives.
- Up to tens of GB and a few analysts: export Parquet on a schedule and query it with DuckDB. Cost is close to zero.
- Dashboards with many concurrent users, data minutes or seconds fresh, or event volumes of thousands of rows per second: ClickHouse, fed in batches by a change-data-capture stream or a queue (change data capture is its own chapter in module four).
- Many teams, many engines, data volumes in the tens of TB: Parquet in object storage under Iceberg or Delta, with a catalog.
What not to do is run the finance dashboard on the primary, and a Postgres read replica is only a partial answer: the queries are as slow there, and long ones either get cancelled by replay conflicts or hold replay back, as the replication chapter showed.
You will time two aggregates in Postgres, copy the shop into DuckDB through its postgres extension, export Parquet and read its metadata, load ClickHouse from both Postgres and Parquet, and then break ClickHouse with small inserts. All new files go in labs/databases/d3-columnar/, except one saved query in labs/databases/shop/queries/.
1. Start the shop at scale 1 and measure the row store.
cd labs/databases
docker compose up -d
docker compose exec -T db psql -U atlas -d shop -c "SELECT count(*) FROM order_items"
# if that prints 0, load it (about 25 s):
docker compose exec -T db psql -U atlas -d shop -f /shop/load.sql
docker compose exec -T db psql -U atlas -d shop -c "
SELECT relname, pg_size_pretty(pg_relation_size(oid)) AS heap,
pg_size_pretty(pg_total_relation_size(oid)) AS with_indexes
FROM pg_class WHERE relname IN ('orders', 'order_items', 'products') ORDER BY relname"order_items heap about 360 MB, orders about 150 MB, products a few MB; the totals with indexes are larger by the primary keys and any indexes earlier chapters created. These are the bytes Postgres has to move for any aggregate that touches every row.2. Time the two queries in Postgres. Create labs/databases/shop/queries/d3-columnar.sql:
\timing on
\echo Q1: 2026 orders by status
SELECT status, count(*) AS n, sum(total_cents) AS cents
FROM orders
WHERE created_at >= '2026-01-01 00:00:00+00'
GROUP BY status ORDER BY status;
\echo Q2: top five categories by revenue
SELECT p.category, sum(i.qty * i.unit_price_cents) AS revenue
FROM order_items i JOIN products p ON p.id = i.product_id
GROUP BY p.category ORDER BY revenue DESC LIMIT 5;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT p.category, sum(i.qty * i.unit_price_cents) AS revenue
FROM order_items i JOIN products p ON p.id = i.product_id
GROUP BY p.category ORDER BY revenue DESC LIMIT 5;Run it twice and keep the second set of timings, so the heap is warm in memory:
docker compose exec -T db psql -U atlas -d shop -f /shop/queries/d3-columnar.sql
docker compose exec -T db psql -U atlas -d shop -f /shop/queries/d3-columnar.sqlorder_items with 2 workers, and the Buffers: shared hit=... read=... on that scan add up to about 44,000 pages: the whole 360 MB heap, to use 16 bytes of each row. Write the two times down.3. Copy the shop into DuckDB through the postgres extension.
mkdir -p d3-columnar && cd d3-columnar
python3 -m venv .venv
.venv/bin/pip install duckdb==1.5.6Create copy.py:
import duckdb, os, time
con = duckdb.connect("shop.duckdb")
con.execute("INSTALL postgres; LOAD postgres;")
con.execute("ATTACH 'host=localhost port=5432 dbname=shop user=atlas password=atlas' "
"AS pg (TYPE postgres, READ_ONLY)")
for t in ["customers", "products", "orders", "order_items", "payments"]:
t0 = time.perf_counter()
con.execute(f"CREATE OR REPLACE TABLE {t} AS FROM pg.public.{t}")
n = con.execute(f"SELECT count(*) FROM {t}").fetchone()[0]
print(f"{t:12} {n:>10,} rows {time.perf_counter() - t0:5.1f} s")
con.execute("CHECKPOINT")
con.close()
print(f"shop.duckdb: {os.path.getsize('shop.duckdb') / 1e6:.0f} MB").venv/bin/python copy.pyorder_items) taking a few seconds, then a file size of roughly 100 to 200 MB for all five tables, against well over 1 GB in Postgres. The first run downloads the postgres extension; behind a proxy that blocks extensions.duckdb.org this step fails, and you can export CSV from psql instead. If you started the shop with SHOP_PORT, change port=5432.4. Run the same queries in DuckDB, on its own storage and on Postgres. Create q.py:
import duckdb, time
Q1 = """SELECT status, count(*) AS n, sum(total_cents) AS cents FROM {s}orders
WHERE created_at >= TIMESTAMPTZ '2026-01-01 00:00:00+00' GROUP BY status ORDER BY status"""
Q2 = """SELECT p.category, sum(i.qty * i.unit_price_cents) AS revenue
FROM {s}order_items i JOIN {s}products p ON p.id = i.product_id
GROUP BY p.category ORDER BY revenue DESC LIMIT 5"""
def run(con, label, sql):
con.execute(sql).fetchall() # warm up
t0 = time.perf_counter()
rows = con.execute(sql).fetchall()
print(f"{label:28} {(time.perf_counter() - t0) * 1000:8.1f} ms first row {rows[0]}")
local = duckdb.connect("shop.duckdb", read_only=True)
run(local, "Q1 DuckDB storage", Q1.format(s=""))
run(local, "Q2 DuckDB storage", Q2.format(s=""))
run(local, "point read, id = 1234567", "SELECT id, status, total_cents FROM orders WHERE id = 1234567")
remote = duckdb.connect()
remote.execute("LOAD postgres")
remote.execute("ATTACH 'host=localhost port=5432 dbname=shop user=atlas password=atlas' "
"AS pg (TYPE postgres, READ_ONLY)")
run(remote, "Q1 DuckDB over Postgres", Q1.format(s="pg.public."))
run(remote, "Q2 DuckDB over Postgres", Q2.format(s="pg.public.")).venv/bin/python q.pyid is clustered, so zone maps skip all but one row group. Over Postgres, both queries take hundreds of milliseconds to a couple of seconds: the vectorised engine is the same, but every byte still comes out of the row heap through COPY. Storage layout is most of the win.5. Export Parquet and read its footer. Create parquet.py:
import duckdb, os
con = duckdb.connect("shop.duckdb", read_only=True)
for t in ["orders", "order_items"]:
con.execute(f"COPY {t} TO '{t}.parquet' (FORMAT parquet, COMPRESSION zstd)")
print(f"{t}.parquet: {os.path.getsize(t + '.parquet') / 1e6:.1f} MB")
con.sql("""SELECT count(DISTINCT row_group_id) AS row_groups, max(row_group_num_rows) AS rows_per_group
FROM parquet_metadata('orders.parquet')""").show()
con.sql("""SELECT path_in_schema AS col, any_value(encodings) AS encodings,
sum(total_compressed_size) AS bytes, sum(total_uncompressed_size) AS raw
FROM parquet_metadata('orders.parquet') GROUP BY col ORDER BY bytes DESC""").show()
con.sql("""SELECT row_group_id, stats_min, stats_max FROM parquet_metadata('orders.parquet')
WHERE path_in_schema = 'created_at' ORDER BY row_group_id LIMIT 4""").show().venv/bin/python parquet.pyorders.parquet about 25 to 40 MB and order_items.parquet about 30 to 50 MB. 17 row groups of 122,880 rows. In the per-column table, status is the smallest by far, a few hundred KB for 2 million values, with a dictionary encoding listed; created_at and customer_id are the largest because they have the most distinct values. The created_at statistics rise from row group to row group without overlapping: that is the clustering that lets a date filter skip row groups, and it is why the same filter on customer_id would skip nothing.6. Start ClickHouse and load it from Postgres and from Parquet. Create compose.yaml in d3-columnar/:
name: d3-columnar
services:
clickhouse:
image: clickhouse/clickhouse-server:26.3.47.6
environment:
CLICKHOUSE_USER: atlas
CLICKHOUSE_PASSWORD: atlas
CLICKHOUSE_DB: shop
ports:
- "8123:8123"
ulimits:
nofile: { soft: 262144, hard: 262144 }
volumes:
- ./:/var/lib/clickhouse/user_files/d3:ro
networks:
default:
name: databases_default # the shop's network, so ClickHouse reaches Postgres as db:5432
external: trueCreate ch-load.sql next to it:
CREATE TABLE products (id UInt64, category LowCardinality(String))
ENGINE = MergeTree ORDER BY id;
INSERT INTO products SELECT id, category
FROM postgresql('db:5432', 'shop', 'products', 'atlas', 'atlas');
CREATE TABLE orders (
id UInt64, customer_id UInt64, status LowCardinality(String), total_cents Int32,
created_at DateTime('UTC'), shipped_at Nullable(DateTime('UTC'))
) ENGINE = MergeTree ORDER BY (created_at, id);
INSERT INTO orders SELECT id, customer_id, status, total_cents, created_at, shipped_at
FROM postgresql('db:5432', 'shop', 'orders', 'atlas', 'atlas');
CREATE TABLE order_items (id UInt64, order_id UInt64, product_id UInt64, qty Int32, unit_price_cents Int32)
ENGINE = MergeTree ORDER BY (order_id, id);
INSERT INTO order_items SELECT * FROM file('d3/order_items.parquet');docker compose up -d
docker compose exec clickhouse clickhouse-client --user atlas --password atlas -d shop \
--queries-file /var/lib/clickhouse/user_files/d3/ch-load.sql
docker compose exec clickhouse clickhouse-client --user atlas --password atlas -d shop \
-q "SELECT table, count() AS parts, sum(rows) AS rows FROM system.parts WHERE database = 'shop' AND active GROUP BY table"orders, about 6,000,000 order_items and 50,000 products, each in a handful of parts that background merges are already combining. If the first command fails with network databases_default not found, the shop stack is not running, or its folder is not called databases; docker network ls shows the real name. Run ch-load.sql once: a second run fails on CREATE TABLE, and to start over use docker compose down -v.7. Query ClickHouse and look at what it read. Open a client:
docker compose exec clickhouse clickhouse-client --user atlas --password atlas -d shopRun each query twice and read the statistics line under the second run:
SELECT status, count() AS n, sum(total_cents) AS cents FROM orders
WHERE created_at >= '2026-01-01 00:00:00' GROUP BY status ORDER BY status;
SELECT p.category, sum(i.qty * i.unit_price_cents) AS revenue
FROM order_items AS i INNER JOIN products AS p ON p.id = i.product_id
GROUP BY p.category ORDER BY revenue DESC LIMIT 5;
SELECT id, status, total_cents FROM orders WHERE id = 1234567;
SELECT name, type, formatReadableSize(data_compressed_bytes) AS on_disk,
round(data_uncompressed_bytes / data_compressed_bytes, 1) AS ratio
FROM system.columns WHERE database = 'shop' AND table = 'orders';Elapsed: 0.02 sec. Processed 0.85 million rows, 7.6 MB: fewer rows than the table holds, because the sparse index on created_at skipped the granules before 2026, and a few MB, because only three columns were read. Q2 processes about 6 million rows and about 100 MB (the three line-item columns it needs, counted uncompressed) in 40 to 150 ms. The point read processes all 2.00 million rows, because id is not the sort key; it is still fast at this size and would not be at a billion. In system.columns, status compresses tens of times over and customer_id barely at all.orders and lower the limits so you do not need 3,000 inserts to reach them: SYSTEM STOP MERGES orders; ALTER TABLE orders MODIFY SETTING parts_to_delay_insert = 150, parts_to_throw_insert = 300;. Then, from a second terminal, insert one row at a time over HTTP: for i in $(seq 1 400); do curl -s -u atlas:atlas 'http://localhost:8123/?database=shop' --data-binary "INSERT INTO orders VALUES ($((3000000 + i)), 1, 'placed', 100, now(), NULL)"; done. The first 150 or so return at once; after that each one takes noticeably longer as the server throttles; and near 300 active parts every insert fails with Code: 252 and TOO_MANY_PARTS. Count them with SELECT count() FROM system.parts WHERE table = 'orders' AND active. Now run SYSTEM START MERGES orders and watch the count fall back to a handful within seconds, then insert 10,000 rows in one statement (INSERT INTO orders SELECT 4000000 + number, 1, 'placed', 100, now(), NULL FROM numbers(10000)) and see the part count rise by one. The fix in production is the same: batch on the client, or turn on async_insert. Reset with ALTER TABLE orders RESET SETTING parts_to_delay_insert, parts_to_throw_insert, and when you are done run docker compose down -v in d3-columnar/; the shop keeps running.The shop's finance and growth teams, eight analysts, run ad hoc SQL against the Postgres primary every morning. Their heaviest queries take 20 to 60 s and checkout p99 latency doubles while they run. Data an hour old is acceptable. The orders and line-item tables total about 15 GB and grow about 50% a year. The engineering team is three people with no data platform. What do you build?
- PAPER C-Store: A Column-oriented DBMS Stonebraker et al., 2005
The design that Vertica, and much of what followed, came from: projections sorted on different keys, per-column encodings, and a write-optimised store in front of the read-optimised one. Skim the sections on the distributed design and K-safety. Read: VLDB 2005; sections 1 to 3 for the architecture and encodings, section 9 for the comparison with a row store.
- PAPER Column-Stores vs. Row-Stores: How Different Are They Really? Abadi, Madden, Hachem, 2008
Measures exactly how much each column-store technique is worth and shows why faking a column store inside a row store fails. The source of the 4.0 s versus 41.0 s numbers in this chapter. Read: SIGMOD 2008; section 5 for the techniques, section 6.3.2 and Figure 7 for the breakdown.
- PAPER MonetDB/X100: Hyper-Pipelining Query Execution Boncz, Zukowski, Nes, 2005
The origin of vectorised execution. Section 3 dissects why tuple-at-a-time engines waste the CPU on TPC-H query 1, which is the argument behind DuckDB's engine. Read: CIDR 2005; sections 3 and 4, including the vector size experiment in 5.1.1.
- PAPER ClickHouse: Lightning Fast Analytics for Everyone Schulze et al., 2024
The ClickHouse developers' own account of MergeTree parts, granules, the sparse index, merges, and how updates and deletes work. Skip the integrations section unless you need it. Read: PVLDB 17; sections 3 (storage, pruning, updates) and 4 (query processing).
- DOC Parquet file format
The short official description of row groups, column chunks, pages, encodings and the footer. Read the pages on encodings and the page index; skip encryption.
- DOC Why DuckDB
The DuckDB authors on in-process analytics and when a server is the wrong shape. Short; follow it with the postgres extension page in the same docs before you build an export job.
- PAPER Lakehouse: A New Generation of Open Platforms that Unify Data Warehousing and Advanced Analytics Armbrust, Ghodsi, Xin, Zaharia, 2021
The argument for table formats over open files as the warehouse, from the Delta Lake authors. Read it with the vendor's interest in mind and section 3.2 on metadata layers closely. Read: CIDR 2021; sections 2 and 3.
- DOC Apache Iceberg table spec
Exactly how snapshots, manifest lists, manifests and the atomic metadata swap work. Read the overview and the sections on snapshots and commits; skip the type and serialisation appendices.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.