A diagnosis-first map of every lever that makes ClickHouse faster, with the version, the evidence, and the trade-off attached to each one.
One ClickHouse query ran in 219 seconds. The same query ran in 139 milliseconds after one optimizer feature kicked in. That is a 1,576Ć gap, and it comes from ClickHouse’s own documentation of lazy materialization, measured on a Top-3 query over the Amazon reviews dataset with cold filesystem caches. The feature has been on by default since v25.4.
Treat that number as a ceiling, not a promise. It is a vendor measurement on one dataset. But it points at the idea behind almost every ClickHouse speedup: the fastest thing the engine can do is read nothing.
Memory is the other half of the story. When Sentry rebuilt its heaviest aggregations, the team reported memory that was 100x lower “and, more importantly, bounded”. Bounded is the word that mattersāand it is the core goal of practical ClickHouse performance tuning. A query that can only use a fixed amount of memory cannot take the node down at 3 a.m.
Most ClickHouse performance tuning guides hand you a flat list of fifteen tips. This one gives you a map instead. You will learn which layer of the engine each technique touches, how to find out which layer your slow query is stuck in, and what each fix costs you. Every number links to the page it came from, and every number is labelled by who measured it.
By the end you will have:
- A five-layer model of ClickHouse I/O that tells you where to look first.
- A repeatable diagnosis workflow built from the official three-run method and a practitioner incident checklist.
- A memory-escape ladder that turns “Memory limit exceeded” into a bounded query.
- A version table, so you can tell whether your cluster has a feature before you chase it.
- A gallery of anti-fixes: the changes that feel productive and make things worse.
One topic is deliberately missing. Deduplication with ReplacingMergeTree, FINAL, and argMax is a tuning problem of its own, and it already has dedicated coverage on this site. You will find the links exactly where they matter.
Key takeaways
Click any topic to expand or collapseThe 30-Second Answer
If you only have half a minute, use this table. It lists the eight levers in the order most teams should reach for them, with the situation each one fits and what it costs you.
| Technique | Use it when | What it costs |
|---|---|---|
| Sort key (ORDER BY) design | Most queries filter on the same few columns. | Fixed at CREATE time. Changing it later means a projection or a rebuild. |
| Narrow types, no blanket Nullable | The schema was inferred or loaded from CSV or JSON. | A one-time type audit. |
| PREWHERE (mostly automatic) | A selective filter sits on small columns while the SELECT touches wide ones. | Nearly free. Confirm with an A/B run. |
Approximate uniq() family | Dashboards and high-cardinality counts. | A typical 1-2% error, per the vendor guide. |
| Deterministic sampling and bit-mask counters | A GROUP BY runs out of memory. | Approximate results and a query rewrite. |
| Async inserts or bigger batches | Many small writers cause too many parts. | Flush delay. Silent loss if you disable wait mode. |
| Materialized views | The same aggregation runs again and again. | Insert-time work. Storage blow-up if the group-by ratio is high. |
| Skip indexes | A filter column correlates with the sort key and nothing else worked. | Index size and upkeep. A last resort. |
What Is ClickHouse Performance Tuning?
ClickHouse performance tuning is the practice of making queries and inserts do less work. You read fewer columns and granules, hold less state in memory, and write fewer parts. It starts by measuring one slow query, finding the stage that dominates, and changing only what controls that stage.
ClickHouse’s own guide builds its advice on three principles: read less data, avoid unnecessary work at query time, and filter first, then process. Those cover most techniques here. This article adds a fourth idea, because the memory evidence from production teams demands it.
- Read less. Skip columns, skip granules, skip rows.
- Compute earlier. Move work from query time to insert time or merge time.
- Filter first. Cut rows before the expensive stage.
- Bound the state (our addition). Keep aggregation and join memory from growing with your data.
If you want the vendor’s own catalogue of techniques, ClickHouse’s definitive query optimization guide is the primary source this article cites most. It is excellent on mechanics. It is silent on failure stories, on version boundaries, and on what to do when your cluster is already on fire. Those gaps are what this article fills.
How ClickHouse Executes a Query: The 60-Second Architecture
Why does the sort key matter so much? Because of how ClickHouse stores data. Four facts explain nearly everything that follows.
- Each column is its own file. A query that needs two columns out of a hundred reads two files.
SELECT *reads all hundred. According to the vendor guide, a wide table queried on a few columns costs about the same as a narrow table.
- The primary index is sparse. It stores one entry per granule, and a granule is 8,192 rows by default. The guide’s example turns an 8.87 million-row table into 1,083 index entries, roughly 97 KB. A B-tree would need an entry per row. Because the index is tiny, it lives in memory, and a binary search over it costs almost nothing.
- A granule is the smallest unit ClickHouse can read. It cannot fetch half of one. Granularity is also adaptive: a new granule starts at 8,192 rows or when the row size reaches 10 MB, whichever comes first.
- Background merges do real work. Aggregation, deduplication, and TTL happen while parts merge. The vendor says this can speed some queries up by 1,000Ć or more. That is a ceiling claim, and it applies when the merge-time work replaces a full query-time computation.
One more fact matters for memory. A query runs as a parallel pipeline, and max_threads defaults to the number of CPU cores. Each thread keeps its own buffers. More threads can mean more memory, which we will use in the memory section.

What Is a Granule in ClickHouse?
A granule is the smallest block of rows ClickHouse can read from a MergeTree table, 8,192 rows by default. The sparse primary index stores one entry per granule, so a query either reads a whole granule or skips it. It can never read half of one.
Two details complete the definition. Granularity is adaptive, so a new granule also starts when the row size reaches 10 MB. And the number of granules read, not the number of rows returned, is what EXPLAIN indexes = 1 reports. That is why granule counts are the honest scoreboard for sort-key work, as the vendor guide shows.
| Layer | What ClickHouse can skip | What you control |
|---|---|---|
| Column files | Every column the query does not name. | Your SELECT list. |
| Partitions | Whole partitions, when the filter touches the partition key. | The PARTITION BY expression. |
| Granules | Blocks of 8,192 rows that the sparse index rules out. | The ORDER BY key. |
| Rows inside a granule | Rows that fail a cheap filter before wide columns load. | PREWHERE and the column types. |
| Late column reads | Wide columns for rows that never reach the final result. | Lazy materialization (v25.4+). |
Coming From Postgres or a Warehouse?
The biggest tuning mistakes in ClickHouse come from habits that are correct elsewhere. The table lists the habit swaps that matter most for performance.
| Habit from Postgres or a warehouse | What to do in ClickHouse | Why |
|---|---|---|
| Normalize tables and join at query time. | Denormalize where the checklist allows. Keep joins cheap when you cannot. | The docs strongly recommend denormalization for latency-sensitive analytics, and a hash join builds its table from the right side. |
| Lead an index with the most selective column. | Lead the ORDER BY with low-cardinality columns. | The index is sparse, not a B-tree: one entry per granule. |
| Update and delete rows freely. | Avoid mutations. Prefer ReplacingMergeTree, lightweight deletes, or DROP PARTITION. | Mutations rewrite whole parts and cannot be rolled back. |
| Insert one row at a time. | Send batches of 10,000 to 100,000 rows, or use async inserts. | Every insert creates a part that background merges must absorb. |
| Add an index to fix any slow filter. | Fix the sort key and types first. Treat skip indexes as a last resort. | Skip indexes only work when the column correlates with the sort key. |
| Accept the default type of an imported column. | Audit types. Schema inference creates Nullable columns. | Every Nullable column adds a hidden mask column. |
Practitioners report the same friction. A thread on r/SQL about tuning ClickHouse for the join-heavy TPC-H benchmark frames the work as four areas: join strategy and memory, the optimizer and statistics, query-level idioms, and table design. That lines up with the sections below. We treat it as a community pattern, not a measurement.
The 5-Layer I/O Optimization Stack
Here is the organizing idea of this article. ClickHouse’s current documentation describes a layered stack of ways to avoid I/O. No ranking third-party article we reviewed uses it as a structure, but it is the cleanest way to decide where to look.
The five layers, in order:
- Columnar storage skips whole columns.
- Sparse primary indexes, skip indexes, and projections skip granules.
- PREWHERE skips rows on filters that no index covers.
- The query condition cache remembers which granules matched a filter last time.
- Lazy materialization delays reading wide columns until the final rows are known.

Layers one and two are design decisions you make once. Layers three to five are mostly automatic in current versions. That split gives you a practical rule: spend your human effort on layers one and two, and spend your measurement effort checking that three to five are working.
Case Study: Lazy Materialization on the Amazon Reviews Dataset
- Challenge: A Top-N query asks for the three reviews with the most helpful votes. The table has wide text columns. Without help, ClickHouse reads those wide columns for far more rows than the query returns.
- Action: Lazy materialization, documented by ClickHouse and introduced in v25.4, reads the sort column first. It fetches the wide columns only for the surviving rows. It is on by default and controlled by
query_plan_optimize_lazy_materialization. - Outcome: The documented example went from 219 seconds to 139 milliseconds, a 1,576Ć speedup, measured with cold filesystem caches. The ClickHouse engineering blog on lazy materialization explains the mechanism. The same page reports far less data read and far lower peak memory on a table of about 151 million rows: roughly 71 GB down to about 1.8 GB read, and 1.11 GiB down to 3.80 MiB of peak memory.
- Lesson: Unlike indexes and PREWHERE, it helps even when the query has no filter at all. Queries with a small LIMIT over wide columns benefit most. This is a vendor measurement on one dataset, so verify on yours. To confirm the feature applied, run EXPLAIN on the query and look for the lazily read columns line the page describes.
now() and today(). These are vendor measurements on the vendor’s examples.Which Version Do You Need?
Check this table before you chase a feature. Every row comes from current official documentation.
| Version ⇅ | Performance-relevant change ⇅ | Why you care ⇅ |
|---|---|---|
| 20.3 | join_algorithm='auto' introduced. | Older JOIN advice may assume manual choice. |
| 24.2 | Adaptive async-insert busy timeouts. | Insert latency became variable, by design. |
| 24.12 | query_plan_join_swap_table introduced with default auto. Before it, the right table was always the build table. | The planner can choose the hash-join build side for ALL-strictness JOIN … ON. |
| 25.4 | Lazy materialization, on by default. | Top-N over wide columns got much cheaper. |
| 25.6 | Lightweight _part_offset projections that behave like secondary indexes, and filtering by more than one projection. | Projections can act as secondary indexes without copying full rows. |
| 25.9 | Allocation profiling rework (jemalloc). | Better memory forensics. |
| 25.12 | JOIN reordering and optimizer statistics on by default. | Manual join-order tricks age out. |
| 26.1 | Compact PROJECTION ... INDEX ... TYPE basic syntax for lightweight projections. | Secondary-index-style projections are easier to define. |
| 26.2 | tokenbf/ngrambf deprecated in favor of text indexes. Async-insert deduplication automatic. | Do not build deprecated indexes. |
| 26.3 | Column statistics generally available, on by default. | The planner has real data to work with. |
| 26.8 | Statistics materialized on insert by default. Docs recommend 26.8+ for JOIN optimization. max_insert_threads default changes from 1 to auto (CPU cores). | A sensible upgrade target for join-heavy work. Parallel inserts can change how many parts an insert creates. |
| 26.10 | Robin Hood hashing for large hash tables, spilling for IN subqueries, an experimental columns cache, string filters applied while reading, Top-K dynamic filtering, and hard JOIN limits that stop hash-based JOINs instead of spilling further (a legacy setting restores the old behavior). | Less memory for GROUP BY, uniqExact, DISTINCT and JOIN. A join that used to push on past a limit can now stop. |
| 26.11 | parallel_hash becomes an obsolete alias of hash. | Update configs that name it. |
How to Diagnose Slow ClickHouse Queries (Don’t Guess)
Where does the time actually go? Most tuning goes wrong right here. People change a setting, rerun the query, see it get faster because the cache is warm, and declare victory.
Why This Query Is Slow
ClickHouse CTO Alexey Milovidov describes the right habit in his performance-analysis talk, quoted on the official tips page: ask why this particular query took five seconds. Medians and averages hide it. As he puts it, he only cares about his query.
That is the same discipline we argue for in profile before you optimize. The tool changes from pandas to ClickHouse. The rule does not: measure first, then touch things.
Step 1: Find the Query Pattern Worth Fixing
The documented workflow, covered in the monitoring section of ClickHouse’s definitive guide, starts from system.query_log. Group by normalized_query_hash so repeated shapes collapse into one row. The docs make the point that optimizing a query that runs 10,000 times a day has 10,000 times more impact than a one-off. That is a vendor tip, not a measured result, but the logic holds.
How to find slow queries in ClickHouse:
Query system.query_logfor finished queries (type = 'QueryFinish').- Group by
normalized_query_hashand rank by total time, not single-run time. - Pick the median run of a pattern, one with typical
read_rowsandread_bytes. - Run
EXPLAIN indexes = 1on it and read the granule counts. - Isolate the bottleneck with the three-run method below.
SQL (adapted from the documented workflow):
SYSTEM FLUSH LOGS; SELECT normalized_query_hash, count() AS runs, sum(query_duration_ms) AS total_ms, max(query_duration_ms) AS slowest_ms, formatReadableSize(max(read_bytes)) AS max_read, formatReadableSize(max(memory_usage)) AS max_memory, any(query) AS example_query FROM system.query_log WHERE type = 'QueryFinish' AND event_time > now() - INTERVAL 1 DAY GROUP BY normalized_query_hash ORDER BY total_ms DESC LIMIT 20;clusterAllReplicas and set skip_unavailable_shards = 1 so a down replica does not break the report.Step 2: Isolate the Bottleneck With Three Runs
The official bottleneck-isolation guide describes a method almost nobody writes about. You run the query three ways and compare the medians.
First, turn off the caches that would flatter your results. These are the session settings the guide uses:
SQL (settings from the official guide):
SET enable_filesystem_cache = 0; SET use_query_cache = 0; SET use_query_condition_cache = 0; SET optimize_use_implicit_projections = 0;Then run three variants. Repeat each one, keep warm-up runs out of the measured set, and take the median. Give every run its own query_id so you can find it in the log:
- Run A: the original query.
- Run B: the grouped count. Keep the GROUP BY, replace the aggregate calculations with
count(), and remove later steps such as sorting and output formatting. If the query has no GROUP BY, skip this run and compare A with C. - Run C: the ungrouped count. Remove the GROUP BY and return a single
count(). Leave FROM, JOIN, PREWHERE, and WHERE unchanged.

| Compare | The gap tells you | Look at next |
|---|---|---|
| Run C alone | Scan, filter, and JOIN cost. | Sort key, types, PREWHERE. |
| Run B minus run C | Grouping cost. | Group-by cardinality, memory ladder. |
| Run A minus run B | Aggregate math, sorting, and output formatting. | Aggregate functions, ORDER BY, LIMIT, result size. |
The guide labels these as diagnostic estimates, so compare medians and never single timings. Two traps are worth knowing. Removing aggregate expressions can remove columns from the read, so compare read_bytes across runs or run B will look cheaper than it is. And the four SET statements above do not switch off the OS page cache or every ClickHouse cache, so state which caches you left on. Validate any fix with EXPLAIN and the query log.
Step 3: Read EXPLAIN Like a Receipt
EXPLAIN indexes = 1 shows which index sections ran and what they kept. Look for Parts: N/M and Granules: N/M. The first number is what survived and the second is what existed. Two documented examples show what good looks like:
- In the Stack Overflow posts example, a good sort key read 39 of 7,578 granules.
- In the skip-index example, the Skip section kept 23 of 8,513 granules.
If the output has no Indexes section and read_rows is close to the table size, you are doing a full scan. That is your answer.
SQL:
EXPLAIN indexes = 1 SELECT count() FROM posts WHERE CreationDate >= '2024-01-01' AND PostTypeId = 'Question';Here is what that looks like in practice. The output below is documented in ClickHouse’s primary-key guide for the same Stack Overflow query, first on a table with no usable key, then on a table ordered by (PostTypeId, toDate(CreationDate)). Notice what is missing from the first one.
Documented output, posts_unordered: no Indexes section, so a full scan:
āāexplaināāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā Expression ((Project names + Projection)) ā ā Aggregating ā ā Expression (Before GROUP BY) ā ā Expression ā ā ReadFromMergeTree (stackoverflow.posts_unordered) ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāDocumented output, posts_ordered: PrimaryKey kept 39 of 7,578 granules:
āāexplaināāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā Expression ((Project names + Projection)) ā ā Aggregating ā ā Expression (Before GROUP BY) ā ā Expression ā ā ReadFromMergeTree (stackoverflow.posts_ordered) ā ā Indexes: ā ā PrimaryKey ā ā Keys: ā ā PostTypeId ā ā toDate(CreationDate) ā ā Condition: and((PostTypeId in [1, 1]), (toDate(CreationDate) in [19723, +Inf))) ā ā Parts: 14/14 ā ā Granules: 39/7578 ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāThe First 15 Minutes of a Performance Incident
An incident is different from an investigation. The cluster is slow now, and you need triage before you need a theory. No official page gives you an incident order. Practitioners do. A thread on r/Clickhouse about the system-table queries people run first describes a pattern: see what is running, kill the offender, check replica lag, then count parts. We read that as a community pattern, not verified fact. Below it is merged with the official three-run method, which is the step the community checklist lacks.
system.processes ordered by elapsed time. Note the memory column.KILL QUERY WHERE query_id = 'ā¦' on the query that is eating memory or threads.absolute_delay and queue_size in system.replicas.system.parts by table. A table with a climbing part count is heading for “too many parts.”SQL (adapted community pattern):
SELECT query_id, user, round(elapsed) AS seconds, formatReadableSize(memory_usage) AS memory, substring(query, 1, 120) AS query_start FROM system.processes ORDER BY elapsed DESC; SELECT database, table, max(absolute_delay) AS max_delay, max(queue_size) AS max_queue FROM system.replicas GROUP BY database, table ORDER BY max_delay DESC LIMIT 10; SELECT database, table, count() AS active_parts FROM system.parts WHERE active GROUP BY database, table ORDER BY active_parts DESC LIMIT 10;Symptom to First Move
Start from what you see. This matrix points each symptom to the stage most likely at fault and to the section that fixes it. It is our synthesis of the documented causes above, not a vendor table.
| Symptom | Likely stage | First move | Where |
|---|---|---|---|
Query slow and read_rows is close to the table size | Scan: the sort key does not match the filter | Read EXPLAIN indexes = 1, then redesign ORDER BY | Layer 1 |
| Slow mainly when selecting wide text columns | Late column reads | Name your columns, check PREWHERE, confirm lazy materialization on 25.4+ | Stack, Layer 3 |
| Memory limit exceeded on a GROUP BY | Grouping: too many distinct groups | Climb the memory-escape ladder | Layer 4 |
| Memory limit exceeded on a JOIN | Join build side too large | Denormalize, rewrite to IN, smaller table on the right, spill settings | Layer 5 |
| Inserts slow, parts climbing, “too many parts” | Ingest: too many small parts | Bigger batches, or async inserts with wait mode on | Ingest |
| Fast alone, slow under concurrent load | Threads multiplying memory (community-reported pattern) | Check threads per query and lower max_threads if memory-bound | Layer 4 |
| Insert latency creeping up after adding a view | Materialized view cost | Run the aggregation-ratio check | Materialized views |
| Added a skip index and nothing changed | No correlation with the sort key | Read the Skip section in EXPLAIN. Drop the index if it prunes nothing | Skip indexes |
Layer 1: Sort Key Design (ORDER BY)
What single decision changes the most about how fast your table queries? The sort key. The vendor’s guide says a well-designed primary key can cut query time by 100Ć or more. Read that as a vendor claim that depends on your workload. The worked examples below show smaller, measurable gains, and they are more honest guides to what you will see.
Two facts to settle first. In MergeTree tables, the PRIMARY KEY must be a prefix of ORDER BY, and most tables define only ORDER BY. And the ordering key is fixed when you create the table. The official guidance says the alternative to getting it wrong is a projection, and that classic projections duplicate data. Lightweight projections are different: since 25.6 they can store only a sorting key plus a _part_offset pointer and behave like a secondary index, and the vendor’s January 2026 engineering post describes granule-level pruning for them.
The Three Rules
- Put the columns your queries filter on most into the key. Look at your real query patterns first. This is why the diagnosis section comes before this one.
- Order the key from low cardinality to high. Start with columns like status, category, or country. End with columns like user ID, timestamp, or session ID.
- Add a time component for time-series data. Where it sits depends on your filters.
Rule two is the one that feels wrong. In OLTP databases you lead with the selective column. In ClickHouse the first key column gets a binary search that works at any cardinality, but later columns use a generic exclusion search. Its power depends on the cardinality of the columns before it. ClickHouse’s performance tips put the rule in one line: few unique values first, many last. If a UUID comes first, filters on the later columns barely skip anything.
toStartOfHour or toStartOfDay, so the key can actually group rows. The trade-off is lost precision for filters finer than the rounding, so compare the cardinality of each option first.SQL (adapted from the official cardinality comparison):
SELECT uniq(CreationDate) AS exact_seconds, uniq(toStartOfHour(CreationDate)) AS hours, uniq(toDate(CreationDate)) AS days FROM posts;Remember the left-prefix behavior too. If your key is (project_id, ts) and a query filters only on ts, ClickHouse has to check nearly every granule. OneUptime’s primary-key write-up is an independent secondary source that shows the same behavior, and it matches the primary docs.
How to choose an ORDER BY key, step by step:
- List your five most expensive query patterns from
system.query_log. - Count how often each column appears in a WHERE clause.
- Check the cardinality of the top candidates.
- Order them low to high, round any timestamp, and stop at four or five columns.
- Compare
EXPLAIN indexes = 1granule counts before and after.
SQL (adapted; simplified columns and enum values):
-- Full scan: no usable key CREATE TABLE posts_scan ( Id UInt32, PostTypeId Enum8('Question' = 1, 'Answer' = 2, 'Wiki' = 3), CreationDate DateTime, ViewCount UInt32, Title String ) ENGINE = MergeTree ORDER BY tuple(); -- Key built from the filter pattern: low cardinality first CREATE TABLE posts_keyed ( Id UInt32, PostTypeId Enum8('Question' = 1, 'Answer' = 2, 'Wiki' = 3), CreationDate DateTime, ViewCount UInt32, Title String ) ENGINE = MergeTree ORDER BY (PostTypeId, toDate(CreationDate));Case Study: Two Official ORDER BY Rewrites
- Challenge: Queries on large tables scanned almost every row, even when the filter was selective.
- Action: ClickHouse’s documentation rebuilt the key around the filter pattern in two examples: Stack Overflow posts (about 59.55 million rows) and the UK Price Paid dataset, covered in the definitive guide (27.64 million rows).
- Outcome: Both are vendor measurements, shown in the table below.
- Lesson: The gain comes from the key matching the filter. The sort key did not get “better” in general. It got aligned to one query pattern.
| Dataset | Before | After | Result |
|---|---|---|---|
| Stack Overflow posts | ORDER BY tuple(): full scan of about 59.8M rows, 361.34 MB, 0.055 s. | ORDER BY (PostTypeId, toDate(CreationDate)): 196.53K rows, 1.77 MB, 0.013 s. 39 of 7,578 granules read. | 4Ć faster |
| UK Price Paid | Key (postcode, address), filter on town: 27.64M rows, 44 ms, 44.21 MB. | Key (town, price): 81,920 rows, 5 ms, 13.03 MB. 99.7% of the table skipped. | 8.8Ć faster, 3.4Ć less data |
Hands-On Check: One Filter, Two Sort Keys
Vendor numbers are one thing. To watch the granule scoreboard on a live engine, we also ran a small check ourselves. It is a hands-on observation, not a benchmark: chDB 4.4.0 (an embedded ClickHouse engine, version 26.9.2.1), 4 million synthetic rows, one part per table after OPTIMIZE TABLE ... FINAL, and no timings. Both tables hold identical data, and the same filter returned 169,684 rows from each.

| Table | ORDER BY | Granules read | Rows read | Bytes read | Indexes section in EXPLAIN |
|---|---|---|---|---|---|
events_scan | tuple() | 489 of 489 | 4,000,000 | 20,000,000 | Absent: full scan |
events_keyed | (event_type, toDate(ts)) | 22 of 489 | 174,336 | 871,680 | PrimaryKey, binary search |
The keyed table read about 23 times fewer rows and bytes. That is a ratio from one synthetic dataset, so do not generalize it. What generalizes is the shape of the evidence: the full-scan table has no Indexes section, and the keyed table reports Granules: 22/489. Here is the setup, so you can repeat it on your own version.
SQL (hands-on check: setup and the query):
CREATE TABLE events_scan (event_type Enum8('click' = 1, 'view' = 2, 'buy' = 3, 'refund' = 4), user_id UInt32, ts DateTime, payload String) ENGINE = MergeTree ORDER BY tuple(); CREATE TABLE events_keyed (event_type Enum8('click' = 1, 'view' = 2, 'buy' = 3, 'refund' = 4), user_id UInt32, ts DateTime, payload String) ENGINE = MergeTree ORDER BY (event_type, toDate(ts)); INSERT INTO events_scan SELECT CAST(1 + intHash32(number) % 4 AS Enum8('click' = 1, 'view' = 2, 'buy' = 3, 'refund' = 4)), intHash32(number + 7) % 100000, toDateTime('2024-01-01 00:00:00') + intDiv(number * 13, 10), repeat('x', 20) FROM numbers(4000000); INSERT INTO events_keyed SELECT * FROM events_scan; OPTIMIZE TABLE events_scan FINAL; OPTIMIZE TABLE events_keyed FINAL; EXPLAIN indexes = 1 SELECT count() FROM events_keyed WHERE ts >= '2024-02-20' AND event_type = 'refund';Observed EXPLAIN output on ClickHouse 26.9.2.1 (events_keyed, plan-tree layout):
Aggregating ā Keys: ā Aggregates: count() ā Skip merging: 0 āāāReadFromMergeTree (lab.events_keyed) Read type: Default Parts: 1 | Granules: 22 Output: Empty Prewhere filter Prewhere filter column: event_type = 'refund' AND ts >= '2024-02-20' Indexes: PrimaryKey Keys: event_type toDate(ts) Condition: and((event_type in [4, 4]), (toDate(ts) in [19773, +Inf))) Parts: 1/1 Granules: 22/489 Search Algorithm: binary search Ranges: 1Parts and Granules lines; the rest is layout.Layer 2: Schemas That Shrink I/O
Smaller columns mean fewer bytes to read, decompress, and hold in memory. The vendor guide claims the right data types can cut storage by 50 to 90%. That is again a workload-dependent vendor claim, but the direction is certain. The official data-type guidance says compression depends on three things together: the ordering key, the data types, and the codecs.
The Nullable Trap
Every Nullable column carries a second, hidden column: a UInt8 mask that records which rows are null. That means extra storage, extra memory, and a mask check on each operation. The guide says it almost always hurts performance.
Here is the catch most teams miss. Schema inference maps columns to Nullable by default. So a table created from a CSV or a JSON file is full of Nullable columns that nobody chose.
Audit before you change anything. The guide’s taxi example found zero nulls in vendor_id, so the Nullable wrapper was pure cost. It found 137,946,731 nulls in mta_tax, so that column had to stay. Let the data decide. Where nulls do exist, the vendor guide suggests a sensible default such as an empty string, zero, or the epoch, if your semantics allow it. That is a business decision as much as a performance one.

SQL:
-- Does this Nullable column ever hold a null? SELECT countIf(vendor_id IS NULL) AS nulls, count() AS total FROM trips; -- Official type-audit one-liner. Run it on a subset: it is expensive on a full table. SELECT * APPLY min, * APPLY max, * APPLY uniq FROM trips FORMAT Vertical;The Right-Sizing Ladder
Use the smallest type that fits the real range. The table below summarizes the documented choices. It also keeps the honest caveat from the docs: test before you assume. One documented column showed no benefit from LowCardinality.
| Pattern | Costly default | Cheaper choice | Documented reason |
|---|---|---|---|
| Inferred integers | Nullable(Int64) | UInt8, UInt16, UInt32 or UInt64, chosen by range | Smallest bit-width that fits. Unsigned if no negatives. |
| Repeated short strings | String | LowCardinality(String) | Under about 10,000 unique values use dictionary encoding. A 12-byte value becomes a 4-byte reference. |
| Timestamps | DateTime64(6) | Date, DateTime, or DateTime64(3) | Use microseconds only if you need them. Date is 16 bits. |
| Finite sets | String | Enum8 or Enum16 | Smaller, and it validates values at insert time. |
| Monotonic numbers | Default codec | CODEC(Delta, Default) | Used on ID and count columns in the official optimized schema. |
| Fixed-length text | String | FixedString(N) | Only when the length is truly fixed. |
Layer 3: Query Optimization Rewrites (PREWHERE, uniq, and Hashing)
Do the queries you already have read more than they need to? Often yes. Four rewrites repay the effort.
PREWHERE: Filter Small Columns First
PREWHERE reads the filter columns first. It then reads the other columns only for rows that passed. It shines when the filter is selective, the filter columns are small, and the SELECT list includes large text fields.
You rarely write it by hand. optimize_move_to_prewhere is on by default and moves suitable conditions for you. The PREWHERE documentation shows a way to measure the effect: run the same query with the setting off and on.
In the vendor’s example, data read fell from 27.67 GB to 16.28 GB (41% less) and time from 96 to 61 seconds (36% faster). A manual PREWHERE gives guaranteed behavior if you do not trust the automatic move.
SQL (A/B method from the PREWHERE docs):
SELECT Title, Body FROM posts WHERE CreationDate >= '2024-01-01' SETTINGS optimize_move_to_prewhere = 0; SELECT Title, Body FROM posts WHERE CreationDate >= '2024-01-01' SETTINGS optimize_move_to_prewhere = 1;Approximate Functions: Fixed Memory for a Small Error
uniq() uses a HyperLogLog sketch of about 12 KB. According to the vendor guide it runs 10 to 100 times faster than COUNT(DISTINCT), with a typical error of 1 to 2%. uniqCombined() merges well across distributed nodes. uniqExact()stays available when you need exact numbers.
uniq() for everything a human only reads.SQL:
SELECT uniq(user_id) AS visitors_approx FROM events; SELECT uniqExact(user_id) AS visitors_exact FROM events;Hash Long Strings Before Grouping
The vendor guide reports that grouping on cityHash64 of long strings is 5 to 10 times faster for strings longer than about 20 to 30 characters. In our judgment, use this when you only need counts and can live with a tiny hash-collision risk. Keep a lookup table if you need the original text back.
Aggregate in Sort Order
For huge GROUP BYs, the vendor guide describes multi-pass grouping: aggregate in stages so that no single stage holds every group. It applies only when the inner GROUP BY matches the table’s sorting key, and optimize_aggregation_in_order must be enabled. The guide says it helps by avoiding disk spilling, which makes it a close cousin of the memory ladder in the next section.
SQL (illustrative):
SELECT cityHash64(url) AS url_hash, count() AS hits FROM events GROUP BY url_hash ORDER BY hits DESC LIMIT 10; SELECT event_type, count() FROM events GROUP BY event_type SETTINGS optimize_aggregation_in_order = 1;The SELECT * Rule
Columnar storage punishes SELECT * more than a row store does, because each extra column is another file to read. Name your columns. A wide table is cheap to query narrowly and expensive to query broadly. With lazy materialization on, a small LIMIT softens the damage, but it does not remove it.
Layer 4: Fixing “Memory Limit Exceeded” and GROUP BY Memory
Why does a query that scans fine suddenly die with “Memory limit exceeded”? Often it is not the scan. The official knowledge-base entry on this error names two common causes: large JOINs and aggregations on high-cardinality fields. This section covers the second, and the JOIN section covers the first.
First decide which problem you have. ClickHouse’s performance tips separate a memory problem (too many groups) from a scan problem (too many rows), and the fixes differ.
The exception carries error code 241. The official knowledge-base entry lists those causes and the spill settings. Limits also stack in layers: a server-wide cap (max_server_memory_usage), a per-user cap (max_memory_usage_for_user), and a per-query cap (max_memory_usage). The knowledge-base entry does not walk through that hierarchy, but OneUptime’s independent write-up on the error does. Whichever cap trips first ends the query.
Case Study: How Sentry Made Memory Bounded
- Challenge: Sentry is an error-tracking platform that, per ClickHouse’s community tips page, processes billions of events daily from more than 4 million developers. Searches and replay queries ran out of memory. The team pinned the cause on one thing: the cardinality of the grouping key. Grouping on combinations such as user, error message, and URL path created millions of aggregation states.
- Action: Two moves, described in Sentry’s own engineering talk. First, deterministic sampling with
WHERE cityHash64(user_id) % 10 = 0, which keeps the same 10% of users in every query. Second, bit-mask aggregation: replace a GROUP BY on high-cardinality strings withsumIf(1, condition)counters, so memory per group is a fixed N counters of 8 bytes. - Outcome: The page reports that a 10% sample cuts memory by about 90% at roughly 5% accuracy for most aggregations. After the bit-mask rewrite, Sentry reported the heavy queries as more than 10x faster and memory 100x lower, and bounded. Their largest customers stopped seeing errors on replay searches. These are company-reported results, quoted on a vendor page.
- Lesson: Memory problems are aggregation-state problems, not scan problems. Bounded memory beats a bigger machine.
The Memory-Escape Ladder
cityHash64(user_id) % 10 = 0, so results stay consistent between runs.sumIf(1, condition) counters. Memory becomes fixed.max_bytes_before_external_group_by and max_bytes_before_external_sort. The query finishes, slower.
SQL (adapted from the Sentry patterns):
-- Rung 3: deterministic sample (same 10% of users every time) SELECT error_message, count() AS hits FROM events WHERE cityHash64(user_id) % 10 = 0 GROUP BY error_message; -- Rung 4: bit-mask counters instead of a high-cardinality GROUP BY SELECT project_id, sumIf(1, level = 'error') AS errors, sumIf(1, level = 'warning') AS warnings, sumIf(1, status = 'unresolved') AS unresolved FROM events GROUP BY project_id;SQL (rung 5; set values for your node):
SET max_bytes_before_external_group_by = 10000000000; -- illustrative: about 10 GB SET max_bytes_before_external_sort = 10000000000; -- illustrative: about 10 GBuniqExact over 100 million values went from 13.5 GB to 4.6 GB and from 1.33 s to 0.31 s. That is a vendor example, not a promise for your data. It does mean the cheapest rung on this ladder may be upgrading, so check your version first.Concurrency Multiplies Memory
Threads are the quiet multiplier. Each thread keeps its own buffers, and max_threads defaults to your CPU core count. If memory is tight, lowering it is a legitimate lever. Practitioners on r/Clickhouse also describe slowdowns that appear only at higher request rates. We read that as a community pattern. Check how many threads your slow query actually used rather than guessing, and read EXPLAIN PIPELINE, where “Ć N” shows the parallelism.
The memory-hunting side of diagnosis is short. Start with the server metrics, then look for queries that already failed:
SQL:
SELECT metric, value FROM system.metrics WHERE metric LIKE '%Memory%'; SELECT event_time, query_id, substring(query, 1, 100) AS query_start, exception FROM system.query_log WHERE exception LIKE '%Memory limit%' ORDER BY event_time DESC LIMIT 10;Now plug in your own numbers. The formulas below are rough planning math, not documented internals. The sampling estimate assumes your group count shrinks roughly with the share of users kept, and the bit-mask figure comes straight from the “N counters of 8 bytes” pattern Sentry described.
Bit-mask memory ā outer groups Ć N counters Ć 8 bytes
Layer 5: JOINs in the Optimizer Era
The oldest ClickHouse advice about JOINs is still the best: avoid them when you can. The official guidance calls denormalization strongly recommended for latency-sensitive analytics, because a hash join builds an in-memory table from the right side of the join.
When Denormalizing Is Right
The documentation gives a checklist. Denormalize when:
- the dimension tables change infrequently,
- the relationship is not many-to-many,
- you query only a limited subset of the columns, and
- you can push the join work upstream, for example into a stream processor.
If you cannot meet those, keep the JOIN and make it cheap.
Case Study: Two Official JOIN Rewrites
- Challenge: Joins that read too much data and held too much in memory.
- Action: ClickHouse’s documentation benchmarked two rewrites on ClickHouse Cloud 26.8.1 with
max_threads=4, the median of five runs, one warm-up, alternated query order, and the query caches turned off. Rewrite one replaced anANY INNER JOINused only as an existence test withIN. Rewrite two filtered both sides before joining. - Outcome: Rewrite one went from 27.101 s and 970.01 MiB to 10.206 s and 162.81 MiB: 2.7Ć faster with 83% less peak memory. Rewrite two went from 0.850 s to 0.696 s: 18% faster with 14% less memory. These are vendor measurements.
- Lesson: The big win came from asking the database for less. The rewrite is only equivalent when the left-hand join key is unique. An ANY
INNER JOINkeeps at most one left row per key (with the defaultany_join_distinct_right_table_keys = 0), while IN keeps every left row that has a match. Check that before you adopt it, and copy the methodology for your own tests.

SQL (illustrative; posts.Id is unique, so the two forms return the same count):
-- Before: a join used only to test existence SELECT count() FROM posts AS p ANY INNER JOIN votes AS v ON p.Id = v.PostId; -- After: an existence test (you cannot select columns from the right side) SELECT count() FROM posts WHERE Id IN (SELECT PostId FROM votes);Other Rules That Pay Off
- Use
LEFT ANY JOINwhen you need only one match per left row. UseINorLEFT SEMI JOINfor existence tests. - Leave
join_use_nulls = 0, the default. It fills unmatched rows with type defaults and avoids Nullable wrappers. Turn it on only when you must tell “unmatched” from “default value.” - Use a dictionary with
dictGetfor repeated key lookups, or aJointable engine for a reusable in-memory lookup. A dictionary on the right side also enables thedirectalgorithm. The docs warn that a layout with a simple key converts the key toUInt64, so you may need a complex-key layout to join on a narrower integer column. - Join on sort keys when you can, so
full_sorting_mergeskips its sort.
Choose the Algorithm
The default is join_algorithm = 'direct,hash,ie_join', and the first one that applies wins. Override it only when you have measured a reason.
| join_algorithm | Use it when | Memory profile | Watch out for |
|---|---|---|---|
direct | The right side is a dictionary or key-value store and you join on a single equality. | Low. No hash table to build. | It needs a key-value-style right side and one equality condition on its single-column key. Otherwise ClickHouse moves to the next algorithm without an error. |
hash | The right table fits in memory. This is the everyday choice. | Builds a hash table from the right side. | Keep the smaller table on the right as the safe habit. Since 24.12, query_plan_join_swap_table = auto lets the planner pick the build side, but the docs limit it to ALL strictness with a JOIN … ON clause. Since 26.11, parallel_hash is an obsolete alias. |
full_sorting_merge | You join on the sort keys of both sides. | Lowest of all when both tables are already stored in key order. Higher when it has to sort. | Gains vanish if the join key is not a sort key. |
grace_hash | The right side is too big for memory and you want a speed and memory trade-off. | Tunable with grace_hash_join_initial_buckets. | Buckets double up to grace_hash_join_max_buckets, then the query fails. |
partial_merge | Memory matters more than time. | Minimal. | Slow. Sorts the right table into blocks with a min-max index. |
For memory-bound joins, the spill settings are max_bytes_before_external_join and max_bytes_ratio_before_external_join. If you set both, the smaller one applies, and a temp path must be configured. One change deserves attention: since 26.10, for hash-based algorithms, reaching a hard limit such as max_rows_in_join or max_bytes_in_join stops the query and never makes the JOIN spill.
Before 26.10, a JOIN that was already running on disk could keep going past those limits by spilling further. If a join that finished on 26.9 fails after an upgrade, check this first. The legacy_join_size_limits_trigger_spilling setting restores the old behavior.
Always verify what the planner chose. EXPLAIN actions = 1 prints an Algorithm line such as HashJoin, FullSortingMergeJoin, or DirectKeyValueJoin. On ClickHouse 26.9.2.1, a LEFT ANY JOIN in our small check printed SpillingHashJoin(ConcurrentHashJoin), so do not expect the older names to match exactly.
SQL:
EXPLAIN actions = 1, compact = 1, pretty = 1 SELECT o.order_id, c.segment FROM orders AS o LEFT ANY JOIN customers AS c ON o.customer_id = c.customer_id;Observed output for the query above on ClickHouse 26.9.2.1 (synthetic tables in a database named lab: 1,000,000 orders, 100,000 customers; trimmed):
Join (JOIN FillRightFirst) ā o[no_stats~1000000] ā c[no_stats~100000] ā Type: left | Strictness: any | Algorithm: SpillingHashJoin(ConcurrentHashJoin) ā Cost: estimated 100.00 thousand ā Output rows: estimated 1.00 million ā Left: rows estimated 1.00 million ā Right: rows estimated 100.00 thousand ā Join conditions: customer_id = customer_id āāāReadFromMergeTree (lab.orders) ā Parts: 1 | Granules: 123 āāāReadFromMergeTree (lab.customers) Parts: 1 | Granules: 12The no_stats markers mean no column statistics existed for either table in this check, so the planner fell back on row-count estimates. That is a small reminder of why the statistics defaults from 26.3 and 26.8 matter.
The Optimizer Era
Here is the freshness point most older articles miss. JOIN reordering and optimizer statistics became default in 25.12. Column statistics went generally available in 26.3. Since 26.8, eligible tables materialize statistics on insert. The documentation’s own advice is to use ClickHouse 26.8 or later for JOIN optimization.
So hand-tuned join order, a staple of older tuning posts, is aging out. Before you spend a week reordering joins, check your version and let the planner try.
Ingest Tuning: Fewer, Bigger, Asynchronous
If you read only one community thread before tuning inserts, make it the one where practitioners trade stories about their biggest ClickHouse bottlenecks. One recurring answer is that moving to async inserts gave the largest single improvement. That is a community report, but several other threads on batching, multi-tenant ingest, and CDC tuning say the same thing in different words.
The Batching Rule
The official knowledge base gives the numbers. Send at least 1,000 rows per batch, and aim for 10,000 to 100,000. Target about one synchronous insert per second. Why? Every insert creates at least one part, and background merges have to keep up.
What “Too Many Parts” Really Means
The message says merges are processing significantly slower than inserts. It fires on one of two limits: parts_to_throw_insert for parts per partition, and max_parts_in_total for the whole table. The settings reference gives the current defaults, which are listed in the table below.
The documented causes are short:
- Many small synchronous inserts.
- A high-cardinality partition key.
- Inserts that span many partitions at once.
- Merges starved by slow storage, a full disk, or CPU and I/O contention.
Diagnose with system.parts for active parts per partition, system.merges for what is merging now, and the server log. The parts query in the incident runbook above is the right first step.
ClickHouse also slows inserts down before it starts rejecting them, so the first threshold works as an early warning. Compare your tables with all three.
| Setting | Default | Counts | What happens when exceeded |
|---|---|---|---|
parts_to_delay_insert | 1000 | Active parts in one partition | Inserts are artificially slowed. |
parts_to_throw_insert | 3000 | Active parts in one partition | Inserts fail with a ‘too many parts’ exception. |
max_parts_in_total | 100,000 | Active parts across the whole table | Inserts fail with the same exception. |
SQL (adapted): where do you stand against the tripwires?:
SELECT name, value FROM system.merge_tree_settings WHERE name IN ('parts_to_delay_insert', 'parts_to_throw_insert', 'max_parts_in_total'); SELECT database, table, partition, count() AS active_parts FROM system.parts WHERE active GROUP BY database, table, partition ORDER BY active_parts DESC LIMIT 20;Part count also affects reads. FINAL, for instance, gets more expensive as unmerged parts pile up. We keep that cost model in one place: our FINAL vs argMax deduplication benchmark covers it, along with a published benchmark where the two approaches landed far apart on time and data read.
Async Inserts: The Server Does the Batching
With async_insert = 1, ClickHouse buffers small inserts on the server and flushes them as one part. Per the asynchronous inserts documentation, a buffer flushes on whichever limit hits first.
| Setting | Default | What it does |
|---|---|---|
async_insert_max_data_size | 100 MiB | Flush when the buffer reaches this size. |
async_insert_busy_timeout_ms | 200 ms (1000 ms on Cloud) | Flush after this wait. |
async_insert_max_query_number | 450 | Flush after this many buffered inserts. |
async_insert_threads | 16 | Threads that flush buffers. |
wait_for_async_insert | 1 (recommended) | Acknowledge only after the flush. Setting 0 is fire-and-forget. |
async_insert_use_adaptive_busy_timeout | On since 24.2 | Timeout adapts between 50 ms and the 200/1000 ms ceiling. |
Five behaviors surprise people:
- Latency is adaptive. Since 24.2 the busy timeout moves between 50 ms and its ceiling, so insert latency varies by design.
- Errors surface at flush, not at receive. One bad row rejects the whole buffered payload.
- Buffers are per insert shape and per node. Different column lists use different buffers.
- Partitions still count. Each flush creates at least one part per distinct partition value, so a high-cardinality partition key can still produce too many parts.
- New rows are invisible until the flush. Data sitting in the buffer cannot be queried yet.
Since 26.2, insert deduplication is automatic (deduplicate_insert = enable). On plain MergeTree you also need non_replicated_deduplication_window above zero. Before maintenance or shutdown, run SYSTEM FLUSH ASYNC INSERT QUEUE. The docs call async inserts the modern replacement for Buffer tables, and they cite benchmarks where the approach scales to hundreds of clients. Read that as a vendor benchmark claim.

async_insert = 1 and keep wait_for_async_insert = 1.system.asynchronous_insert_log, and you only see them if you look. Keep the default of 1.SQL:
ALTER USER ingest_user SETTINGS async_insert = 1, wait_for_async_insert = 1; INSERT INTO events SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (now(), 'click', 42); SYSTEM FLUSH ASYNC INSERT QUEUE;max_insert_threads defaults to auto, which resolves to the number of CPU cores (it was 1 before). The settings reference says this parallelizes INSERT SELECT by default and can also parallelize the write side of a plain INSERT, and the release notes warn that it can change the number of parts created and the order of inserted rows. After an upgrade, re-check part counts on tables fed by INSERT SELECT. To restore the old behavior, set max_insert_threads = 1 or use a compatibility setting below 26.8.If your source is a database, the ingest path matters as much as the settings. Our walkthrough of a Postgres to ClickHouse CDC pipeline and our notes on Postgres CDC in production show where batching decisions meet real replication. One r/Clickhouse thread on tuning a PeerDB CDC pipeline reports the same theme: dense, well-batched inserts are how you avoid the dreaded too-many-parts error.
Mutations: Write Amplification in Disguise
ALTER ... UPDATE and DELETE do not edit rows in place. The mutations guidance explains that they rewrite entire parts, cannot be rolled back, and continue after a restart unless you run KILL MUTATION. A SELECT that runs mid-mutation can see a mix of mutated and unmutated parts. Watch system.mutations. Prefer ReplacingMergeTree or CollapsingMergeTree, lightweight deletes, or DROP PARTITION where they fit.
SQL:
SELECT database, table, mutation_id, command, create_time, is_done FROM system.mutations WHERE NOT is_done;Partitioning and Skip Indexes: Tools, Not Magic
These two features have the worst ratio of reputation to reliability in ClickHouse. Each is useful. Neither is a speed button.
Partitioning Is Lifecycle Management
The official partitioning guidance says partitioning is primarily a data management technique and not a query optimization tool. What does it buy you?
DROP PARTITIONis a cheap metadata operation, so retention is fast.- It integrates with TTL and with tiered storage, from hot SSD to object storage.
- ClickHouse builds MinMax indexes on partition columns, so filters on those columns can prune whole partitions.
What does it cost? Merges happen inside a partition, so a high-cardinality key leaves many small unmerged parts, which is a direct route to “too many parts.” Queries that cross many partitions can get slower, not faster.
The documentation gives slightly different counts. The definitive guide says 10 to 100 partitions, and the partitioning-keys page says under roughly 100 to 1,000 distinct values is usually fine. A safe summary: keep it in the hundreds at most, never thousands. The guide also reserves partitioning for tables above roughly 10 GB with a clear retention need. If you are unsure, start with no partitioning and add it from observed access patterns.
Community advice looks different. One r/Clickhouse thread on multi-tenant observability suggests monthly partitioning plus large inserts. Both views can be true. Monthly partitions are good for insert and retention hygiene. They are not a scan-speed feature. If you work across table formats, partition design that survives production shows how the same lifecycle-first logic applies to Iceberg.
Skip Indexes Are a Last Resort
ClickHouse’s skip-index documentation ranks them after data types, the primary key, and materialized views. They only work when the indexed column correlates with the primary key, or when your inserts cluster the data. The mechanism explains why: if even one matching value sits in a block, the whole block still has to be read. Used blindly, they add cost for no gain.
Case Study: A 60Ć minmax Index That Worked for a Reason
- Challenge: A query filtering on
ViewCountand a date over the Stack Overflow posts table, about 59.55 million rows, still had 8,513 granules left to read after the primary index did its work. - Action: The docs add a
minmaxskip index, then runMATERIALIZE INDEX. Without that step, existing parts have no index data. - Outcome: The query went from 0.720 s over 59.55M rows to 0.012 s over 39.11K rows, about 60Ć faster (our arithmetic from the page’s timings).
EXPLAINshowed the Skip section keeping 5 of 123 parts and 23 of 8,513 granules. This is a vendor measurement. - Lesson: It worked because
ViewCountcorrelates withCreationDate, which sits in the sort key. Take that correlation away and the same index would prune little.
SQL (adapted from the documented example):
ALTER TABLE posts ADD INDEX view_count_idx ViewCount TYPE minmax GRANULARITY 1; ALTER TABLE posts MATERIALIZE INDEX view_count_idx; EXPLAIN indexes = 1 SELECT count() FROM posts WHERE CreationDate > '2009-01-01' AND ViewCount > 10000000;tokenbf_v1 and ngrambf_v1 have been deprecated since 26.2 in favor of text indexes. Many tutorials still teach them as current. If you are about to create one, check the docs for the text index first. Even ClickHouse’s own January 2026 engineering guide still lists them without a deprecation note, which fits a guide that predates 26.2 (our inference from the dates).| Index type | Fits | Note |
|---|---|---|
minmax | Numeric or date columns that move with the sort key. | Cheap. The 60Ć example above. |
set(N) | Columns with few distinct values per block. | Documented as effective when each block holds few distinct values. |
bloom_filter | Rare values you must find, such as error codes or specific IDs, in columns that are high-cardinality overall but low-cardinality within a block. | Lower granularity skips more but grows the index. Measure both. |
text | Natural-language or free text that needs precise token lookup and multi-term search. | The recommended replacement for tokenbf and ngrambf since 26.2. |
tokenbf_v1, ngrambf_v1 | Legacy full-text approaches. | Deprecated since 26.2. Avoid in new tables. |
Materialized Views and Projections: Compute Earlier
Moving work from query time to insert time is the “compute earlier” idea, and materialized views are the main tool. The docs order the work: types and primary key first, views after. Views are also where teams get hurt.
Two Kinds of Materialized View
According to ClickHouse’s materialized-view best practices:
- Incremental views run on each insert and process only the new block. The docs say they have no appreciable impact on cluster performance in most cases, support all aggregations, and scale to very large datasets.
- Refreshable views re-run a query on a schedule, in
REPLACE(default) orAPPENDmode. They suit top-N caches and complex joins.
One rule for refreshable views: never refresh more often than the query takes. A 10-second refresh on a 10-second query piles up load on itself.
Case Study: CommonRoom’s 20 GB to 190 GB View
- Challenge: CommonRoom built a materialized view on a raw log table of about 20 GB. The view grew to 190 GB, nearly 10 times larger than its source. The team had created one row per attribute, and each log can carry ten attributes. The story comes from ClickHouse’s materialized-view tips and Kirill Sapchuk’s CommonRoom talk.
- Action: The failure became a rule, in the page’s words, that a GROUP BY producing more rows than it removes builds “an expensive index, not a materialized view.” The page also gives a pre-flight check: divide distinct group count by total rows.
- Outcome: The documented outcome is the size blow-up itself. The public record does not state the exact fix or the resulting size, so we do not guess. This is a production report.
- Lesson: Views move compute to insert time. An unbounded GROUP BY moves a lot of it, all the time.

Run the check below before you create a view. Under 10% means good compression. Over 70% means explosion risk.
SQL (adapted from the official pre-check pattern):
SELECT uniq(tenant_id, attribute_key) AS groups, count() AS total_rows, round(groups / total_rows * 100, 2) AS aggregation_ratio FROM raw_logs;The same page lists four warning signs of a view that is hurting you:
- Insert latency climbing from about 10 ms to 100 ms or more.
- “Too many parts” errors that keep coming back.
- CPU spikes during inserts.
- Insert timeouts.
To catch the first sign early, track insert latency over time and compare it before and after you add a view.
SQL (adapted): insert latency by hour:
SELECT toStartOfHour(event_time) AS hour, quantile(0.5)(query_duration_ms) AS p50_ms, quantile(0.95)(query_duration_ms) AS p95_ms, count() AS inserts FROM system.query_log WHERE type = 'QueryFinish' AND query_kind = 'Insert' AND event_time > now() - INTERVAL 7 DAY GROUP BY hour ORDER BY hour;Materialized View or Projection?
ClickHouse’s comparison is the clearest source. Use the table to choose.
| Projection | Materialized view | |
|---|---|---|
| Storage | Stored alongside the main table. Classic projections duplicate the data. Lightweight _part_offset projections store only the sorting key plus an offset. | Separate target table you design. |
| Updates and routing | Updated asynchronously. The optimizer picks a projection automatically. | Updated synchronously on insert, or on a schedule if refreshable. |
| Query features | No JOINs or WHERE in the definition. No chaining. | Supports JOINs, WHERE, and chaining. |
| Engines and schema | MergeTree only. | Explicit schema control. |
| UPDATE and DELETE on the source | Incompatible with lightweight-deleted rows by default. lightweight_mutation_projection_mode (v24.7+) can enable compatibility. | The view does not react, so it can go stale. |
| FINAL queries | Do not work with FINAL. | Unaffected by that limit. |
| Parallel replicas | Not supported. | Supported. |
| Failure handling | Handled silently. | An INSERT failure can lose the view’s data. |
| Version note | Since 25.6, queries can filter by more than one projection. | None. |
In practice, reach for a projection when you need another sort order or a filter on a column outside the primary key and you can no longer change the key. Reach for a materialized view when you aggregate into a target table, transform data, or need JOINs. The two are not either-or.
query_plan_optimize_lazy_materialization = false when you are checking projection compatibility. Treat that as a diagnostic toggle, not a default.Evidence Rules Used in This Guide
Every number in this guide carries an evidence label. Performance articles go wrong when they mix measurements with opinions without saying which is which. This table is the contract for the whole page.
| Evidence class | What it means here | Examples in this article |
|---|---|---|
| Documented capability | Behavior and defaults stated in official ClickHouse documentation or knowledge-base pages. | Granule size, async-insert defaults, part-count defaults, version milestones, setting names. |
| Vendor measurement | A benchmark published by ClickHouse, reported with the conditions the vendor gives. | 219 s to 139 ms (lazy materialization), 2.7Ć JOIN rewrite, 60Ć skip index, Robin Hood hashing. |
| Production report | A lesson that a named company or practitioner reported publicly. Community threads are treated as patterns, not proof. | Sentry’s memory results, CommonRoom’s 20 GB to 190 GB view. |
| Hands-on observation | Something we ran ourselves. | One small synthetic check on ClickHouse 26.9.2.1: rows and granules read for two sort keys, and one JOIN plan. No timings and no benchmark claims. The validation lab below shows how to repeat it. |
Caches and Hardware Reality
Do your benchmark numbers mean anything if the cache answered the question? Often they do not.
ClickHouse has many caches. The performance documentation covers them:
- Mark cache for MergeTree marks and an uncompressed cache.
- The OS page cache, which you do not control directly.
- A query cache for repeated query results.
- A query condition cache, which remembers matching granules.
- A filesystem cache for data on S3 or Azure object storage.
A Benchmark-Honesty Checklist
The vendor’s JOIN benchmarks model the right habits. Copy them when you test your own changes:
- Pin the version and the thread count (
max_threads). - Do one warm-up run, then take the median of several runs.
- Alternate the order of the variants so neither benefits from running second.
- Turn off
use_query_cacheanduse_query_condition_cache, or say that you left them on. - Compare the same data, and quote read rows and bytes alongside time.
For wider comparisons, ClickBench is ClickHouse’s public analytical benchmark, and it publishes methodology and reproduction instructions. We use it here as a methodology reference only, and we quote none of its leaderboard numbers.
The Host Still Matters
ClickHouse reads and merges a lot of data, so the operating system’s memory behavior counts. Our guide to OS-level memory tuning for database hosts covers swappiness and dirty ratios. If you want the theory behind marks and caches, how cache eviction policies work explains why a hot working set matters.
Where This Fits in the Wider Stack
The same read-less logic shows up well outside ClickHouse. Columnar engines outside the database follow the same logic. Our Polars vs pandas benchmarks on a 10 GB dataset show it in a different tool, and the useful lens there is columnar engines beyond the database. If you are comparing OLAP engines, how the same workload maps to Apache Doris is a useful contrast for CDC-fed analytics.
Common Mistakes That Cost Weeks
Every item here looks reasonable in the moment. That is why they cost weeks. Each row maps the mistake to its fix and to the section that explains it.
| Mistake | Why it hurts | Fix | Where |
|---|---|---|---|
1. SELECT * on wide tables | Every column is another file to read. | Name only the columns you need. | Layer 3 |
| 2. Nullable everywhere | Hidden mask column, extra memory, extra checks. Schema inference creates them for you. | Audit nulls, then drop the wrapper where none exist. | Layer 2 |
| 3. Timestamp first in ORDER BY | A near-unique first column weakens skipping on everything after it. | Low cardinality first, and round the time. | Layer 1 |
| 4. Partitioning by a high-cardinality column | Merges are per partition, so parts pile up. | Partition for lifecycle. Hundreds at most, never thousands. | Partitioning |
| 5. A skip index on every column | Without correlation to the sort key it adds cost and skips little. | Use minmax on columns that track the sort key. Prove it with EXPLAIN. | Skip indexes |
| 6. Raising part limits as the first fix | Delays the error, adds metadata overhead, slows queries. | Batch bigger or use async inserts. | Ingest |
7. Scheduling OPTIMIZE FINAL | Forces heavy merges as a routine job. | Read why scheduled OPTIMIZE FINAL backfires before you automate it. | Ingest |
| 8. GROUP BY on three high-cardinality columns | Millions of aggregation states in memory. | Climb the memory-escape ladder. | Layer 4 |
| 9. Fire-and-forget async inserts | Failed flushes lose data without telling the client. | Keep wait_for_async_insert = 1. | Ingest |
| 10. Judging by averages or warm-cache reruns | Hides the slow query and flatters the fix. | Isolate one query. Control the caches. | Diagnosis |
Your First Week of Tuning: A 7-Day Plan
You do not need a quarter. You need a week and the discipline to change one thing at a time.

Before and After
The table shows the transformation you are aiming for, using documented examples from this article. They come from other people’s data, so they are illustrations of direction, not promises.
| Area | Before | After | Evidence |
|---|---|---|---|
| Sort key | Full scan of about 59.8M rows. | 196.53K rows read. | Vendor measurement, 4Ć faster |
| Memory | Millions of aggregation states. | Bounded counters. | Sentry-reported, memory 100x lower |
| JOIN | ANY INNER JOIN: 27.101 s, 970.01 MiB. | IN: 10.206 s, 162.81 MiB. | Vendor measurement, 2.7Ć faster |
| Wide reads | Wide columns read for every candidate row. | Wide columns read for surviving rows only. | Vendor measurement, 219 s to 139 ms |
| Views | Aggregation ratio above 70%. | Ratio under 10%. | Official thresholds |
| Ingest | Many tiny synchronous inserts. | 10,000 to 100,000 rows per batch, or async with wait mode on. | Documented guidance |
ORDER BY tuple() and one with a designed key, then compare EXPLAIN indexes = 1 granule counts. (2) Toggle optimize_move_to_prewhere. (3) Run the aggregation-ratio query on one of your tables. (4) A/B max_bytes_before_external_group_by on a heavy GROUP BY. (5) Run EXPLAIN actions = 1 on a JOIN and read the Algorithm line. Every step uses settings documented in this article.Summary: The ClickHouse Tuning Decision Rule
The fastest thing ClickHouse can do is read nothing, and the slowest thing it can do is hold everything. Everything in this guide is a way to move your queries toward the first and away from the second.
If you remember only one rule, make it this: measure one query, find its stage, fix that stage, and prove it with a number you controlled. Sort keys and schemas decide most outcomes. The optimizer handles more every release, so check your version before you hand-tune. Treat memory as a cardinality question, treat part counts as a health metric, and treat “add an index” or “add partitions” as suspicious until EXPLAIN says otherwise.
One limit to name plainly: the numbers here are vendor measurements and company-reported results, plus one small synthetic check of our own (rows and granules read, no timings). We ran no benchmarks. That is why the validation lab exists.
Where next? If deduplication is your pain, start with why CDC deduplication lag happens and then our FINAL vs argMax deduplication benchmark. For schema and warehouse modeling trade-offs beyond ClickHouse, see our data warehouse interview scenarios. Subscribe if you want the next ClickHouse deep dive when it lands.
ClickHouse Performance Tuning: FAQs
What is ClickHouse performance tuning?
ClickHouse performance tuning is the practice of making queries and inserts do less work: reading fewer columns and granules, holding less state in memory, and writing fewer parts. It begins with measuring one slow query and finding which stage dominates, using system.query_log to rank patterns and the three-run isolation method to split their cost.
Why is my ClickHouse query slow?
Usually one of three stages: scanning and filtering, grouping, or aggregate and sort work. Split the cost with the three-run method, then read EXPLAIN indexes = 1. If it shows no Indexes section and read_rows is near the table size, the query is doing a full scan and the sort key does not match your filter.
What is the difference between the primary key and ORDER BY in ClickHouse?
The PRIMARY KEY must be a prefix of ORDER BY, and most tables define only ORDER BY. The ordering key sets the physical sort order and drives the sparse index. It is fixed at table creation, so choose it from your real filters and put low-cardinality columns first.
How do I fix “Memory limit exceeded” in ClickHouse?
Treat it as a cardinality problem. Filter first, group on fewer or coarser keys, sample deterministically, then use bit-mask counters. Set max_bytes_before_external_group_by to spill if needed, and add memory last. The knowledge-base entry names large JOINs and high-cardinality aggregations as the common causes.
How many partitions should a ClickHouse table have?
Keep it in the hundreds at most, never thousands. The vendor documents partitioning as a data management tool, not a speed feature, and a high-cardinality key creates many unmerged parts. If you are unsure, start with no partitioning and add it from observed access patterns.
Should I use async inserts or client-side batching?
Batch on the client when you can: 10,000 to 100,000 rows, about one insert per second. Use async inserts when many small writers make that impossible, and keep wait_for_async_insert = 1. Setting it to 0 risks silent data loss, which the docs call very risky.
Should I use a materialized view or a projection?
Use a projection for simple, automatic speedups on a single table. Use a materialized view when you need JOINs, a WHERE filter, chaining, or full schema control. Check the aggregation ratio first: over 70% means the view will behave like an expensive index. Read the official comparison for the full feature list.
Should I raise parts_to_throw_insert to fix “too many parts”?
Not as the first fix. The official knowledge base says raising part limits does not address the cause, and it advises changing them only after you have found the cause and confirmed capacity. Raising them first delays the error, adds metadata overhead, and slows queries. Send bigger batches, use async inserts, or fix a high-cardinality partition key. Read the too many parts entry for diagnostics.
Was this article helpful?










[…] For the same evidence-first mindset applied to general query speed, finding the pattern worth fixing in system.query_log, isolating the bottleneck with three runs, and reading EXPLAIN like a receipt, see our ClickHouse performance tuning guide. […]
[…] evidence points inside ClickHouse rather than at the kernel, the fixes become query-level work: our ClickHouse performance tuning guide covers reducing GROUP BY and JOIN memory, the memory-escape ladder, and max_threads before you buy […]
[…] budget for the read side too: FINAL and argMax queries carry a query-time cost, and our guide to ClickHouse performance tuning shows how to diagnose slow queries, memory limits, and ingest before changing […]
[…] the query-engine side of that stack, our ClickHouse performance tuning guide covers the ClickHouse equivalent, sort-key design, PREWHERE, and memory limits, and how to tell […]
[…] For a concrete engine walkthrough of this diagnose-first process, from query-log analysis and column pruning to sort keys, projections, and memory limits, see our guide to ClickHouse performance tuning […]