ClickHouse
MergeTree parts and merges, sorting keys and sparse indexes, partitions, ReplacingMergeTree, materialized views, and mutations.
10 questions
JuniorTheoryVery commonHow do ORDER BY and PRIMARY KEY differ in a MergeTree table?
How do ORDER BY and PRIMARY KEY differ in a MergeTree table?
ORDER BY sets the on-disk sort order and is the primary key if none is given. PRIMARY KEY must be its prefix and is what the sparse index stores. Neither is unique — duplicates are stored; dedup needs ReplacingMergeTree or query logic.
Common mistakes
- ✗Treating the MergeTree primary key as a unique constraint like in PostgreSQL
- ✗Thinking ORDER BY only orders query results rather than the data on disk
- ✗Listing PRIMARY KEY columns that are not a prefix of ORDER BY
Follow-up questions
- →When is it worth making
PRIMARY KEYshorter thanORDER BY? - →How would you read the latest row per key when keys are not unique?
JuniorTheoryVery commonIn a MergeTree table, what is a data part, and what do background merges do?
In a MergeTree table, what is a data part, and what do background merges do?
Each INSERT writes a new immutable part — rows sorted by the sorting key, stored column by column. Background merges combine small parts of the same partition into larger ones; engine work such as replacing or summing rows happens only then.
Common mistakes
- ✗Thinking an INSERT appends rows to an existing part instead of creating a new one
- ✗Expecting row replacement or summing to happen at insert time rather than at merge time
- ✗Assuming a merge can combine parts from different partitions
Follow-up questions
- →Why do many tiny INSERTs hurt a MergeTree table even when total volume is small?
- →What happens to the source parts after a merge has finished?
MiddleDebuggingVery commonWhy does a ReplacingMergeTree engine table still return duplicate keys after an update?
Why does a ReplacingMergeTree engine table still return duplicate keys after an update?
Older versions of an ORDER BY key are dropped only when parts merge, at an unknown time; two INSERTs are still two parts. Read with FINAL (a query-time merge, cheaper with a key filter) or argMax by updated_at. OPTIMIZE … FINAL is not a per-query fix.
Common mistakes
- ✗Expecting ReplacingMergeTree to deduplicate at insert time
- ✗Running OPTIMIZE … FINAL after inserts as a per-query fix
- ✗Falling back to ALTER UPDATE mutations instead of inserting a new version
Follow-up questions
- →Why does a filter on the
ORDER BYkey makeFINALcheaper? - →How would you delete an order from a
ReplacingMergeTreetable without a mutation?
JuniorTheoryCommonHow do ALTER … UPDATE/DELETE mutations differ from a lightweight DELETE?
How do ALTER … UPDATE/DELETE mutations differ from a lightweight DELETE?
A mutation rewrites every part holding affected rows, runs asynchronously by default and is not atomic across parts. Lightweight DELETE only marks rows in the hidden _row_exists column; merges drop them later. Neither fits frequent edits.
Common mistakes
- ✗Expecting ALTER UPDATE/DELETE to change rows in place like an OLTP database
- ✗Assuming a lightweight DELETE frees disk space as soon as it returns
- ✗Applying a stream of row updates as many small mutations
Follow-up questions
- →How do
mutations_syncandsystem.mutationshelp you track a mutation? - →How would you model frequent order status changes without any mutations?
MiddleTheoryCommonWhat makes a ClickHouse incremental materialized view run, and what never reaches it?
What makes a ClickHouse incremental materialized view run, and what never reaches it?
It is an insert trigger: on each block inserted into its left-most source table it runs its SELECT and writes the result to a target table (TO). Existing rows, joined tables, mutations and merges never reach it, so totals can drift from FINAL.
Common mistakes
- ✗Thinking an incremental view periodically recomputes over the whole source table
- ✗Expecting inserts into a joined right-side table to update the view
- ✗Assuming merges or mutations on the source propagate into the view
Follow-up questions
- →Why does a materialized view over a
ReplacingMergeTreesource double-count updated rows? - →Why is the
TOtarget-table pattern preferred over the view's implicit inner table?
MiddleDesignCommonA ClickHouse events table (MergeTree) takes about 2 billion rows a day, inserted in batches of roughly 50,000 rows every couple of seconds. Almost every query filters by user_id and a time range of a few days, and data older than 13 months must be removed. One teammate proposes PARTITION BY user_id (about 5 million users) so per-user queries open less data; another proposes PARTITION BY toStartOfHour(event_time). Choose the partition key and the ORDER BY for this table, and explain what goes wrong with each of the two proposals.
A ClickHouse events table (MergeTree) takes about 2 billion rows a day, inserted in batches of roughly 50,000 rows every couple of seconds. Almost every query filters by user_id and a time range of a few days, and data older than 13 months must be removed. One teammate proposes PARTITION BY user_id (about 5 million users) so per-user queries open less data; another proposes PARTITION BY toStartOfHour(event_time). Choose the partition key and the ORDER BY for this table, and explain what goes wrong with each of the two proposals.
A partition is a data-management unit (drop, TTL), not an index, and merges never cross it. A user_id key splits each batch into thousands of parts; both keys yield thousands of partitions, past the docs' ~1000. Partition by month; ORDER BY (user_id, event_time).
Common mistakes
- ✗Using PARTITION BY as if it were an index for the most common filter
- ✗Assuming merges will fold many small partitions together over time
- ✗Choosing a partition key without counting how many parts each insert creates
Follow-up questions
- →How does a monthly partition key make the 13-month retention cheap?
- →What happens to an INSERT whose batch spans more than 100 partitions?
MiddlePerformanceCommonHow does ClickHouse's sparse primary index skip granules, and when does it skip almost none?
How does ClickHouse's sparse primary index skip granules, and when does it skip almost none?
The index keeps one mark per granule (8192 rows by default). A filter on a key prefix binary-searches the marks and skips granules; one on a later column behind high-cardinality ones excludes almost none. Put filtered, low-cardinality columns first.
Open full question →Common mistakes
- ✗Treating the sparse index as a B-tree with one entry per row
- ✗Expecting a filter on any ORDER BY column to skip granules as well as a prefix filter does
- ✗Putting a high-cardinality column such as user_id first when queries filter by other columns
Follow-up questions
- →How does
EXPLAIN indexes = 1show how many granules a query kept? - →When does a data-skipping index or a projection help a filter that misses the key prefix?
MiddleDebuggingCommonInserts fail with "Too many parts" after a switch to one row per INSERT — why, and what is the fix?
Inserts fail with "Too many parts" after a switch to one row per INSERT — why, and what is the fix?
Each one-row INSERT makes a part, faster than merges combine them. Past 1000 active parts in a partition inserts are delayed, past 3000 (300 before 23.6) they fail. Batch on the client or enable async_insert (on since 26.2); a higher limit only hides it.
Common mistakes
- ✗Raising parts_to_throw_insert instead of reducing the number of parts being created
- ✗Quoting the old 300-part threshold that changed in 23.6
- ✗Running OPTIMIZE … FINAL on a schedule to keep up with tiny inserts
Follow-up questions
- →What does
wait_for_async_inserttrade off whenasync_insertis on? - →How would you count active parts per partition in
system.parts?
SeniorTheoryOccasionalA ReplacingMergeTree partitioned by toYYYYMM(updated_at) keeps some keys duplicated forever — why?
A ReplacingMergeTree partitioned by toYYYYMM(updated_at) keeps some keys duplicated forever — why?
Merges only combine parts of one partition, so once an update moves a key to a new month its two versions never collapse on disk, OPTIMIZE … FINAL included. SELECT … FINAL still reconciles them by default, at query-time cost. Partition by an immutable column.
Common mistakes
- ✗Believing OPTIMIZE … FINAL collapses duplicates across partitions
- ✗Assuming SELECT … FINAL also stops at partition boundaries by default
- ✗Partitioning a ReplacingMergeTree by a column that changes on every update
Follow-up questions
- →When does
do_not_merge_across_partitions_select_finalmakeFINALcheaper yet still correct? - →How would you find keys that already have versions in several partitions?
SeniorDebuggingOccasionalA ClickHouse query got 10× slower after the data grew 10× — find the cause
A ClickHouse query got 10× slower after the data grew 10× — find the cause
read_rows grew tenfold with the data: pruning keeps the whole month and the primary key drops no granule, as event_type is outside the (user_id, event_time) key. Parts per partition are normal. Fix: a sort key or projection led by event_type.
Common mistakes
- ✗Blaming hardware or merges without comparing read_rows before and after the slowdown
- ✗Reading successful partition pruning as proof that the primary key is used
- ✗Assuming every column in the WHERE clause benefits from the sorting key
Follow-up questions
- →How would a projection ordered by
event_typechange this query'sEXPLAINoutput? - →Which
system.partsnumbers would point to merges falling behind instead?