ClickHouse MergeTree explained: parts, granules, the sparse primary key and skip indexes
ClickHouse is fast because it reads very little. This guide builds a 10-million-row MergeTree table, shows the primary key reading 2 of 421 granules, and measures how a bloom filter skip index and a projection rescue queries the key cannot serve.
- Reading time
- 13 min
- Sections
- 8
- Code examples
- 6
- Tables
- 4
- Sources
- 6
- Published
- 23 Nov 2026
- What changed
- ClickHouse 26.10 reads less for top-K and join queries
- Why it matters
- Designing a ClickHouse table is mostly designing its ORDER BY.
- What to do
- List your top query filters
ClickHouse is an open-source column-oriented database built for analytical queries over very large tables. Its speed does not come from magic hardware. It comes from a storage engine, MergeTree, that lets a query skip almost all of a table before reading a single value. If you choose the sorting key well, a query over ten million rows touches a few thousand. If you choose it badly, the same query reads everything.
This article explains how MergeTree stores data, how its sparse primary index prunes reads, and what to do when a query filters on a column the key does not cover. Every number below comes from running the examples in an embedded ClickHouse engine (chDB with ClickHouse 26.11), so you can reproduce them.
What happened
ClickHouse 26.10 reads less for top-K and join queries (22 October 2026)
ClickHouse's monthly release 26.10 shipped on 22 October 2026. The changelog lists several improvements that all work through granule pruning, the mechanism this article teaches. GROUP BY key LIMIT n queries over MergeTree tables now publish the boundary of their top-K heap to the reading step, so rows beyond it are dropped before other columns are read. Join runtime filters can now prune granules during the probe phase by default (enable_join_runtime_filters_index_analysis). Primary index analysis also improved for queries that filter on the primary key and on other columns at once, such as WHERE timestamp BETWEEN ... AND level = 'error'.
The legacy query analysis is removed (22 October 2026)
The same release removed the query analysis that preceded ClickHouse's newer analyzer, which had not been selectable since 26.9. The changelog warns that mixed-version clusters can see errors during upgrades, so teams running older initiators should plan rolling upgrades carefully.
How MergeTree stores a table
A MergeTree table is a set of immutable parts. Each INSERT writes a new part: a directory with one or more files per column, sorted by the table's ORDER BY key. In the background, ClickHouse merges small parts into larger ones, like a librarian who receives books in small boxes and periodically shelves several boxes together in order.
Inside each part, rows are grouped into granules. The ClickHouse documentation defines a granule as the smallest indivisible data set streamed into ClickHouse for processing. By default, index_granularity is 8,192 rows, with adaptive granularity also capping a granule by size (10 MB by default for index_granularity_bytes).
For every granule, the primary index stores one entry: the key values of the granule's first row. This is why the index is called sparse. It does not point to rows. It points to blocks of about 8,192 rows. A table of a billion rows needs only around 122,000 index entries, small enough to keep in memory.
Here is the table we will use. It stores events for 1,000 tenants over 90 days:
CREATE TABLE events (
tenant_id UInt32,
event_date Date,
ts DateTime,
event_type LowCardinality(String),
user_id UInt64,
amount Decimal(12,2)
) ENGINE = MergeTree
PARTITION BY toYYYYMM(event_date)
ORDER BY (tenant_id, event_date, event_type);
INSERT INTO events
SELECT number % 1000,
toDate('2026-09-01') + (number % 90),
toDateTime('2026-09-01 00:00:00') + number % (90 * 86400),
['view', 'click', 'purchase'][1 + number % 3],
number % 500000,
(number % 10000) / 100
FROM numbers(10000000);
After an OPTIMIZE TABLE events FINAL, system.parts shows one part per monthly partition:
| Partition | Rows | Marks | Compressed | Uncompressed |
|---|---|---|---|---|
| 202609 | 3,333,340 | 408 | 13.36 MiB | 85.84 MiB |
| 202610 | 3,444,441 | 422 | 13.72 MiB | 88.70 MiB |
| 202611 | 3,222,219 | 395 | 12.98 MiB | 82.98 MiB |
Two lessons are already visible. First, 3,333,340 rows divided by 8,192 is 407 granules, plus one final mark, giving 408 marks. Second, sorting plus columnar compression shrinks about 257 MiB of raw values to about 40 MiB, roughly six to one, because sorted columns contain long runs of similar values.
Partitions are not the main index
PARTITION BY splits data into separate parts by month. It helps with data lifecycle (dropping a whole month is cheap) and can prune whole partitions. But partitions are coarse. The ClickHouse guidance is to keep partition counts modest and rely on the ORDER BY key for selective reads. A common mistake carried over from Hive-style lakes is to partition by day and tenant, which creates thousands of tiny parts that merge slowly.
How the sparse primary key prunes reads
Because data in each part is sorted by (tenant_id, event_date, event_type), ClickHouse can binary-search the index entries to find which granules could contain matching rows. EXPLAIN indexes = 1 shows the result.
EXPLAIN indexes = 1
SELECT sum(amount) FROM events
WHERE tenant_id = 42 AND event_date = '2026-10-13';
The plan reports three stages of pruning:
| Stage | What it uses | Parts kept | Granules kept |
|---|---|---|---|
| Min-max index | event_date range of each part |
1 of 3 | 421 of 1,222 |
| Partition | toYYYYMM(event_date) |
1 of 1 | 421 of 421 |
| Primary key | binary search on (tenant_id, event_date) |
1 of 1 | 2 of 421 |
So the query reads 2 granules out of 1,222, about 0.16 percent of the table, and returns 1,112 rows with a sum of 50,507.04. Only the amount column is read for those two granules, plus the filter columns. That is the whole trick of ClickHouse performance in one table.
Key order matters
A sorted key works like a phone book sorted by surname, then first name. Finding "Smith, Anna" is fast. Finding everyone called "Anna" is not, because Annas are spread across every surname.
The same is true here. Our key starts with tenant_id, so a filter on tenant_id prunes well. A filter on user_id, which is not in the key, cannot use the index at all:
EXPLAIN indexes = 1
SELECT sum(amount) FROM events WHERE user_id = 4242;
Every stage shows Condition: true and the query scans all 1,222 granules.
Rules of thumb from the ClickHouse primary key guidance:
- Put the columns you filter on most often first.
- Within that, prefer lower-cardinality columns earlier, because they create long runs that both prune and compress well.
- Do not add many columns "just in case". Each extra column only helps queries that also filter on every column before it.
- The
ORDER BYkey cannot be changed cheaply later, so design it from real query patterns.
When the key does not fit: skip indexes and projections
Real tables are queried in more than one way. Support wants to look up one user. Finance wants one tenant's month. MergeTree offers two tools for the second access path.
Data skipping indexes
A skip index stores a small summary per block of granules, and ClickHouse skips blocks whose summary proves no row can match. The documented types include minmax, set(N), bloom_filter (default false-positive rate 0.025 if unspecified), and the token and n-gram bloom filters for text.
ALTER TABLE events
ADD INDEX idx_user user_id TYPE bloom_filter(0.01) GRANULARITY 1;
ALTER TABLE events MATERIALIZE INDEX idx_user;
After materializing, the same user_id = 4242 query reads 10 granules out of 1,222 instead of all of them. A bloom filter can say "definitely not here" or "maybe here", never "definitely here". Our user's rows are spread across the table because user_id cycles every 500,000 rows, so the filter keeps the few granules that really contain them, plus any false positives.
Skip indexes only help when matching rows cluster into few granules. If a value appears in almost every granule, the index costs write time and storage and skips nothing. The ClickHouse documentation recommends testing skip indexes on real data before relying on them.
Projections
A projection is a hidden copy of the table, or of an aggregate over it, stored inside each part with a different sort order. The optimizer picks it automatically when it serves a query better.
ALTER TABLE events
ADD PROJECTION by_user (SELECT * ORDER BY user_id);
ALTER TABLE events MATERIALIZE PROJECTION by_user;
Now the plan reads from by_user and the primary key search on user_id keeps 3 granules of 1,222, returning 20 rows with a sum of 848.40. The price is storage: the projection's parts take 66.33 MiB compressed, more than the base table's 40 MiB, because data sorted by user_id compresses less well than data sorted by tenant and date.
| Technique | Read reduction for user_id = 4242 |
Extra storage | Write cost | Best when |
|---|---|---|---|---|
| None (key does not cover column) | 1,222 of 1,222 granules | None | None | Rare queries |
| Bloom filter skip index | 10 of 1,222 | Small | Low | Values cluster in few granules, point lookups |
Projection ordered by user_id |
3 of 1,222 | About 1.7x the base table here | Each insert writes twice | A second hot access path |
| Separate table plus materialized view | Similar to projection | Full copy | Each insert writes twice | Different retention or schema per path |
Continue learning
How this article connects
7 pages link to or from it. Drag to turn, click a dot to open it.
How this compares with other warehouses
Every analytical engine fights the same battle: read less. The mechanisms differ.
| Engine | Main pruning structure | You control |
|---|---|---|
| ClickHouse MergeTree | Sparse primary index per 8,192-row granule, skip indexes, projections | ORDER BY, PARTITION BY, indexes, projections |
| Snowflake | Min-max metadata per micro-partition | Optional clustering keys |
| BigQuery | Partitions and block-level clustering | Partition and cluster columns |
| Amazon Redshift | Zone maps per block, sort keys | Sort and distribution keys |
| Parquet files in a lake | Row group and page statistics | File layout and sort order before writing |
The idea of keeping min and max values per block is shared with Apache Parquet row groups and with lakehouse table formats. ClickHouse is unusual in making the sorted key the centre of the design and in offering projections as an in-engine second sort order. The ClickHouse tool page and the big data engines overview give more context.
What it means in practice
Designing a ClickHouse table is mostly designing its ORDER BY. Write down the five most frequent query filters, check which columns appear in almost all of them, and put those first. Expect to add one projection or a materialized view for a second access path, and budget storage for it. Keep partitions coarse, usually by month, and let the key do the fine pruning.
Make EXPLAIN indexes = 1 part of code review for new dashboards. If the granules line shows most of the table, the query will not scale, no matter how fast it is on today's data. Feeding ClickHouse from Apache Kafka in small batches also creates many small parts, so batch inserts to thousands of rows or more and let merges catch up.
What to do now
- List your top query filters. Pull them from
system.query_logand rank columns by how often they appear inWHEREclauses. - Order the key by filter frequency and cardinality. Put the most common, lower-cardinality filters first.
- Check pruning with
EXPLAIN indexes = 1. Compare granules read with total granules for each important query. - Keep partitions coarse. Use monthly partitions unless you have a strong lifecycle reason for finer ones.
- Try a bloom filter index for point lookups. Materialize it on a copy and confirm it skips most granules on real data.
- Add a projection for a second hot path. Measure its storage on a sample before rolling it out.
- Batch inserts. Avoid many tiny inserts that create small parts and slow merges.
- Review upgrade notes before moving to 26.10 or later. The legacy analyzer removal and other backward-incompatible changes can affect mixed clusters.
Risks and open questions
A wrong ORDER BY is expensive to fix. Changing the sort key usually means creating a new table and reinserting data.
Skip indexes can silently do nothing. If values are spread across most granules, the index adds cost without skipping data; always check the granule counts.
Projections multiply storage and write work. Our projection was larger than the base table, so several projections can triple the footprint.
Synthetic tests flatter results. Our generated data is perfectly regular; real data with skew will prune differently, so test with production samples.
Watch next: how the new top-K and join runtime filter pruning in 26.10 change dashboard workloads that previously needed projections, and how the removal of the legacy analyzer affects long-lived clusters.
Frequently asked questions
What is a granule in ClickHouse?
A granule is a block of rows, 8,192 by default, that ClickHouse reads as a unit. The primary index stores one entry per granule, so pruning decisions are made per granule, not per row.
Why is the ClickHouse primary key called sparse?
Because it holds one index entry for each granule, not one per row. That keeps the index tiny enough for memory while still letting a binary search skip most of the table.
Does the primary key enforce uniqueness?
No. In MergeTree the primary key defines sort order and pruning, not uniqueness. Duplicate key values are allowed; engines such as ReplacingMergeTree deduplicate only during merges.
When should I use a projection instead of a skip index?
Use a skip index when matching rows naturally cluster in a few granules and you want low storage cost. Use a projection when a second filter pattern is frequent and needs a full sort order of its own, and you can afford the extra storage and write time.
Should I partition by day?
Usually not. Partitions are meant for data lifecycle and coarse pruning, and many small partitions create many parts that merge slowly. Monthly partitions plus a good ORDER BY key are the common starting point.
Summary
MergeTree stores each table as sorted, immutable parts split into granules of about 8,192 rows, with a sparse primary index holding one entry per granule. In our 10-million-row example, a filter that matched the key read 2 granules out of 1,222, while a filter on an unrelated column read them all. A bloom filter skip index cut that to 10 granules, and a projection sorted by the other column cut it to 3 at the cost of more storage than the base table. ClickHouse 26.10, released on 22 October 2026, pushes the same pruning idea further into top-K and join queries, so key design remains the most important decision you make.
Sources
- Official ClickHouse Docs: A practical introduction to primary indexes in ClickHouse
- Official ClickHouse Docs: Understanding ClickHouse data skipping indexes
- Official ClickHouse Docs: Choosing a primary key
- Code GitHub: ClickHouse CHANGELOG, release 26.10
- Code GitHub: clickhouse-docs sparse primary index guide source
- Code PyPI: chdb, embedded ClickHouse engine
Cite this article
Kelahmet, Ö. C. (2026, November 23). ClickHouse MergeTree explained: parts, granules, the sparse primary key and skip indexes. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/clickhouse-mergetree-primary-key-granules
BibTeX
@online{kelahmet2026clickhouse,
author = {Kelahmet, {\"O}zer Cem},
title = {{ClickHouse MergeTree explained: parts, granules, the sparse primary key and skip indexes}},
year = {2026},
month = {nov},
url = {https://www.ozercemkelahmet.com/articles/clickhouse-mergetree-primary-key-granules}
}Version historyfirst version
- Published
Factual corrections are listed here with what changed. Wording and formatting edits are not listed.