FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Columnar Databases (ClickHouse / DuckDB)

Compare ClickHouse MergeTree pruning and DuckDB vectorized scans to choose storage, execution, and query layouts for analytical workloads.

Freshness: current•14 min read•Data Engineering and Databases
Full Technical Reference Document

Mental model

Columnar query engines store values by column so a projection reads only fields used by a query, then filters and aggregates batches instead of constructing a full row object for every record. ClickHouse MergeTree adds sorted parts and sparse marks to skip row ranges; DuckDB vectorizes local scans in fixed-size batches. The right engine depends on where the data lives and how queries arrive.

Theory

Row storage keeps fields for one record close together, which is convenient for fetching or updating a complete record. Columnar storage places values for the same field together, so an analytical query that needs a few columns can avoid reading the rest. Values of one type also tend to compress well with encodings such as run length, dictionary, or delta coding. The savings depend on the data and codec; “columnar” does not mean every scan is cheap.

ClickHouse's MergeTree family writes immutable data parts. Within each part, rows are sorted by the table's ORDER BY key, and marks identify granules along that order. The sparse primary index stores key values at mark boundaries, rather than one entry for every row. When a predicate constrains a useful prefix of the sort key, ClickHouse can rule out ranges of marks before reading column data. The default index_granularity targets 8,192 rows per mark interval, although adaptive granularity can change a physical interval based on byte limits.

The sort key therefore controls both compression locality and pruning. A table sorted by (event_date, region, campaign_id) can serve date and region predicates more directly than a query filtering only on an unrelated device_id. An index mark is a boundary used to locate candidate granules, not a guarantee that every row in a surviving granule matches. Skip indexes can summarize additional columns, but they help only when their summaries correlate with the filter and cost less than the reads they avoid.

DuckDB is an in-process analytical database. Its execution engine passes typed vectors through operators; the documented standard vector size is 2,048 tuples. A filter produces a selection of qualifying row positions, and downstream operators can process those vectors without allocating one object per value. DuckDB also reads columnar files and uses row-group statistics when available. Vectorized execution describes how operators work on batches; columnar storage describes how bytes are laid out. They reinforce each other but are separate properties.

Mechanism and implementation boundary

A ClickHouse insert commonly creates a new sorted part. A query first narrows parts using partition metadata, then consults primary key marks and any applicable skipping indexes to choose granules. It reads the requested columns from those granules, decompresses blocks, applies residual predicates, and aggregates results. Background merges combine parts into a better consolidated layout; they consume disk bandwidth and temporarily need space for both input and output.

DuckDB scans the required columns from its table or file source, creates vectors, applies predicates as selection masks, and feeds survivors into joins or aggregates. The vector size bounds the unit of operator work, not the query result size. A selective filter can reduce the rows passed downstream, while an unselective filter may still require reading most candidate values. Both systems benefit from matching data order or row-group boundaries to repeated predicates.

Operational design

Suppose an 800 GB analytical table has 40 similarly sized compressed columns. A query reads event_date, region, campaign_id, and amount; a rough projection estimate is 800 GB × 4 / 40 = 80 GB before pruning. If an order-aligned filter excludes 90% of the candidate granules, the data-column portion could approach 8 GB. The estimate assumes equal column sizes and effective mark pruning. The index, predicate columns, metadata, decompression, and imperfect correlation add work.

Bprojected≈∑j∈RBjB_{\text{projected}} \approx \sum_{j \in R} B_j

Here R is the set of required projection and predicate columns, and B_j is the compressed byte size of column j for the candidate row ranges. Record bytes read, marks or row groups considered, rows filtered, decompression CPU, memory peak, and p95 query latency. For ClickHouse, also track part count and merge backlog. For DuckDB, track temporary spill, memory limits, and whether a query reads local data or remote files.

Failure modes and misconceptions

A poor ORDER BY can leave millions of candidate marks even when a query has a selective predicate. Adding an index over an uncorrelated field may still read almost every granule because each granule's min/max range overlaps the filter. Measure the fraction of marks skipped for the production predicate before adding index structures.

Many small ClickHouse inserts create many parts. Queries then pay planning and merge overhead, and background merges can fall behind under sustained ingestion. Batch writes where latency permits, monitor part age, and leave disk headroom for merges. A mutation that changes stored values often rewrites parts; treat it as expensive maintenance rather than a constant-time row update.

Column pruning does not remove the cost of a required wide column, and compression does not guarantee less CPU. Low-cardinality dictionaries save I/O but require decoding and can complicate joins across different encodings. A wide aggregate may be memory-bound even after pruning. In DuckDB, a local benchmark that fits in memory can hide remote object-store latency or spill behavior in production. In ClickHouse, a single-node benchmark can hide replica coordination and concurrent tenant contention.

Trade-offs

ClickHouse suits continuously ingested, server-side analytical workloads that need shared concurrency, replicas, and predictable operational controls. MergeTree sort order and merge policy must be designed around common access patterns. DuckDB suits embedded analytics, local development, and bounded batch analysis where a process can own the working set. It can query Parquet directly without a service, but that does not make it a drop-in substitute for a multi-tenant serving cluster.

Columnar engines trade row-level update convenience for scan throughput and compression. Choose an order key from frequent filters and groupings, not from a wish list of every query field. Compare identical result semantics and data snapshots; otherwise differences in pruning, late-arriving records, or refresh time can make a fast result incorrect. A hybrid design can keep shared serving in ClickHouse while analysts use DuckDB on extracts or Parquet snapshots.

Decision scenario

An events service receives steady inserts and serves dashboards for many customers. A one-user DuckDB test is faster than the current ClickHouse query, but it reads a local cached file and uses a single process. The production decision should benchmark both systems against the same fresh snapshot, concurrent customer mix, network path, and memory cap. Keep ClickHouse for shared serving if replica availability and tenant isolation are requirements; use DuckDB for local exploration or bounded extracts only after validating freshness and memory limits.

Learning outcomes

  • Explain how ClickHouse sort keys and sparse marks narrow candidate granules.
  • Distinguish vectorized execution from columnar storage and describe DuckDB's vector batches.
  • Estimate projected bytes from required columns and validate the estimate with engine counters.

Quantitative model

For equal-width columns, reading four of forty columns from 800 GB projects roughly 80 GB. If mark pruning then excludes nine tenths of the relevant ranges, about 8 GB of those data columns remain, before index reads and execution overhead. Actual column widths and predicate correlation often dominate this estimate, so compare it with measured bytes per query.

event-date and region predicate
ClickHouse ORDER BY mark pruning
DuckDB row-group pruning
column-vector filter batches
campaign revenue aggregation
Conceptual teaching model synthesized from:clickhouse-mergetree-docs,duckdb-vector-execution-docs

Implementation pattern

This comparison executes one deterministic query against matching snapshots. Keep the database drivers in the analysis environment and use read-only credentials; the result comparison catches layout or refresh mismatches before a latency benchmark.

python
import os
import duckdb
import clickhouse_connect
​
query = """
SELECT campaign_id, count(*) AS events, sum(amount) AS revenue
FROM events
WHERE event_date >= DATE '2026-11-14'
AND region = 'eu-west'
GROUP BY campaign_id
ORDER BY campaign_id
"""
duck = duckdb.connect("events.duckdb", read_only=True)
clickhouse = clickhouse_connect.get_client(
host=os.environ["CLICKHOUSE_HOST"],
username=os.environ["CLICKHOUSE_USER"],
password=os.environ["CLICKHOUSE_PASSWORD"],
database="analytics",
)
duck_rows = duck.execute(query).fetchall()
clickhouse_rows = clickhouse.query(query).result_rows
assert duck_rows == clickhouse_rows, "snapshot results differ"
print(f"Matched {len(duck_rows)} campaign aggregates")
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h 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.

Next