ClickHouse Performance Tuning: Fixing Slow Queries, Memory Limits, and Ingest

ClickHouse performance tuning for 26.x: fix slow ORDER BY scans, Memory limit exceeded, JOIN bottlenecks, and too many parts with real SQL.

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 collapse
Diagnose one query before tuning

Pull the heaviest query pattern from system.query_log, then split its cost with the three-run isolation method.

Put low-cardinality columns first in ORDER BY

It is the opposite of OLTP instinct, and it is the single biggest lever the vendor documents.

Treat Nullable as a cost

Every Nullable column adds a hidden mask column. Schema inference creates Nullable columns by default.

Fix memory errors by cutting group cardinality

Filter first, aggregate higher, sample deterministically, use bit-mask counters, spill to disk, and scale up last.

Send fewer, bigger inserts

Aim for 10,000 to 100,000 rows per batch, or use async inserts with wait_for_async_insert=1.

Do not raise part limits as your first fix

Raising limits for “too many parts” delays the error and makes queries slower. Find the cause first.

Use partitions for lifecycle, not speed

Use skip indexes only when the column tracks your sort key.

Check your version

Lazy materialization, JOIN reordering, and column statistics all changed the defaults between 25.4 and 26.8.

Note: Version boundary
This guide describes current ClickHouse as of November 2026 (the 26.x line). Defaults, behaviors, and benchmark figures were checked against the cited official pages, and most of those pages were re-opened on November 13, 2026. Dated items carry a version number, so check your own version before relying on them. The evidence labels used below (documented capability, vendor measurement, production report, hands-on observation) are defined in Evidence Rules Used in This Guide.

The 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.

TechniqueUse it whenWhat it costs
Sort key (ORDER BY) designMost queries filter on the same few columns.Fixed at CREATE time. Changing it later means a projection or a rebuild.
Narrow types, no blanket NullableThe 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() familyDashboards and high-cardinality counts.A typical 1-2% error, per the vendor guide.
Deterministic sampling and bit-mask countersA GROUP BY runs out of memory.Approximate results and a query rewrite.
Async inserts or bigger batchesMany small writers cause too many parts.Flush delay. Silent loss if you disable wait mode.
Materialized viewsThe same aggregation runs again and again.Insert-time work. Storage blow-up if the group-by ratio is high.
Skip indexesA filter column correlates with the sort key and nothing else worked.Index size and upkeep. A last resort.
Swipe sideways on small screens to see every column.

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.

ClickHouse MergeTree storage architecture showing separate column files and a sparse primary index in RAM pointing to 8192-row granules
A MergeTree part stores each column as its own file; the tiny sparse primary index sits in RAM and points to 8,192-row granules (or 10 MB blocks).

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.

What each layer lets ClickHouse skip
LayerWhat ClickHouse can skipWhat you control
Column filesEvery column the query does not name.Your SELECT list.
PartitionsWhole partitions, when the filter touches the partition key.The PARTITION BY expression.
GranulesBlocks of 8,192 rows that the sparse index rules out.The ORDER BY key.
Rows inside a granuleRows that fail a cheap filter before wide columns load.PREWHERE and the column types.
Late column readsWide columns for rows that never reach the final result.Lazy materialization (v25.4+).
Swipe sideways on small screens to see every column.

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 swaps for people migrating to ClickHouse
Habit from Postgres or a warehouseWhat to do in ClickHouseWhy
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.
Swipe sideways on small screens to see every 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.

ClickHouse is fast because it skips data in layers. Tuning means making each layer skip more.

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:

  1. Columnar storage skips whole columns.
  2. Sparse primary indexes, skip indexes, and projections skip granules.
  3. PREWHERE skips rows on filters that no index covers.
  4. The query condition cache remembers which granules matched a filter last time.
  5. Lazy materialization delays reading wide columns until the final rows are known.
Diagram of the ClickHouse 5-layer I/O optimization stack: columnar storage, sparse indexes, PREWHERE, query condition cache, and lazy materialization
The 5-layer ClickHouse I/O stack: design layers 1 and 2 carefully, then verify layers 3 to 5 are pruning data automatically.

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.

The 5-layer I/O optimization stack (top = cheapest to skip)
1
Columnar storage
Skip every column the query does not name.
2
Indexes and projections
Skip granules using the sparse primary index, skip indexes, or a projection.
3
PREWHERE
Skip rows by filtering small columns before reading wide ones.
4
Query condition cache
Remember which granules matched a filter, so repeats skip them.
5
Lazy materialization (v25.4+)
Defer wide-column reads until the rows that survive are known.
Layer order follows the vendor documentation. The visual is our own summary.

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.
Contrarian insight: Newer wins come from reading even less, automatically
The common story is that you tune ClickHouse by adding things: indexes, views, settings. Between 25.4 and 26.8 the opposite happened. The optimizer learned to read less on its own. A cluster on an old version can look like it needs ten hand-made optimizations when it needs one upgrade.
Note: What 26.10 added to the read-less stack
The 26.10 release adds more ways to read less. According to the vendor’s 26.10 release webinar page, string filters such as LIKE and startsWith are applied while strings are read (275 MB to 5 MB peak memory in its example), Top-K dynamic filtering pushes the ORDER BY … LIMIT boundary into MergeTree scans (9.45 GB to 144 MB read), and the query condition cache now works for filters on 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 milestones (ClickHouse 20.3 to 26.11)
Version ⇅Performance-relevant change ⇅Why you care ⇅
20.3join_algorithm='auto' introduced.Older JOIN advice may assume manual choice.
24.2Adaptive async-insert busy timeouts.Insert latency became variable, by design.
24.12query_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.4Lazy materialization, on by default.Top-N over wide columns got much cheaper.
25.6Lightweight _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.9Allocation profiling rework (jemalloc).Better memory forensics.
25.12JOIN reordering and optimizer statistics on by default.Manual join-order tricks age out.
26.1Compact PROJECTION ... INDEX ... TYPE basic syntax for lightweight projections.Secondary-index-style projections are easier to define.
26.2tokenbf/ngrambf deprecated in favor of text indexes. Async-insert deduplication automatic.Do not build deprecated indexes.
26.3Column statistics generally available, on by default.The planner has real data to work with.
26.8Statistics 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.10Robin 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.11parallel_hash becomes an obsolete alias of hash.Update configs that name it.
Tap a column header to sort. Swipe sideways on small screens to see every column.
Spend effort on sort keys and schemas. Let layers three to five work, and check your version so you know they can.

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:

  1. Query system.query_log for finished queries (type = 'QueryFinish').
  2. Group by normalized_query_hash and rank by total time, not single-run time.
  3. Pick the median run of a pattern, one with typical read_rows and read_bytes.
  4. Run EXPLAIN indexes = 1 on it and read the granule counts.
  5. 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;
Warning: Do not compare optimizations with query_log
The documentation is explicit: historical query-log numbers vary with cache state and system load. Use them to choose a query to investigate. Do not use them to compare before-and-after results. On a cluster, wrap the table in 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.
Diagram of ClickHouse three-run bottleneck isolation comparing Run A, Run B, and Run C to split scan, grouping, and aggregate costs
Isolate where query time goes using three runs: Run C measures scan and JOIN cost, B minus C isolates grouping, and A minus B isolates math and sorting.
How to read the three-run results
CompareThe gap tells youLook at next
Run C aloneScan, filter, and JOIN cost.Sort key, types, PREWHERE.
Run B minus run CGrouping cost.Group-by cardinality, memory ladder.
Run A minus run BAggregate math, sorting, and output formatting.Aggregate functions, ORDER BY, LIMIT, result size.
Swipe sideways on small screens to see every column.

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:

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.

Performance incident runbook
1
See what is running
Query system.processes ordered by elapsed time. Note the memory column.
2
Kill the runaway
Use KILL QUERY WHERE query_id = '…' on the query that is eating memory or threads.
3
Check replica lag
Read absolute_delay and queue_size in system.replicas.
4
Count active parts
Group system.parts by table. A table with a climbing part count is heading for “too many parts.”
5
Rank recent heavy patterns
Run the query-log report above to see which pattern is responsible.
6
Isolate with three runs
Once the fire is out, split the offender’s cost into scan, grouping, and aggregate work.
Steps 1 to 4 follow a community-reported checklist. Steps 5 and 6 follow the official workflow.

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-to-action matrix
SymptomLikely stageFirst moveWhere
Query slow and read_rows is close to the table sizeScan: the sort key does not match the filterRead EXPLAIN indexes = 1, then redesign ORDER BYLayer 1
Slow mainly when selecting wide text columnsLate column readsName your columns, check PREWHERE, confirm lazy materialization on 25.4+Stack, Layer 3
Memory limit exceeded on a GROUP BYGrouping: too many distinct groupsClimb the memory-escape ladderLayer 4
Memory limit exceeded on a JOINJoin build side too largeDenormalize, rewrite to IN, smaller table on the right, spill settingsLayer 5
Inserts slow, parts climbing, “too many parts”Ingest: too many small partsBigger batches, or async inserts with wait mode onIngest
Fast alone, slow under concurrent loadThreads multiplying memory (community-reported pattern)Check threads per query and lower max_threads if memory-boundLayer 4
Insert latency creeping up after adding a viewMaterialized view costRun the aggregation-ratio checkMaterialized views
Added a skip index and nothing changedNo correlation with the sort keyRead the Skip section in EXPLAIN. Drop the index if it prunes nothingSkip indexes
Swipe sideways on small screens to see every column.
Find the pattern with the most total cost, isolate its stage with three runs, then confirm with EXPLAIN. Never judge a change from the query log alone.

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

  1. 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.
  2. 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.
  3. 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.

Warning: The time-granularity trap
A timestamp with microsecond precision is nearly unique per row. Placed early, it makes a weak sort key. The official tips page recommends rounding, with functions such as 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:

  1. List your five most expensive query patterns from system.query_log.
  2. Count how often each column appears in a WHERE clause.
  3. Check the cardinality of the top candidates.
  4. Order them low to high, round any timestamp, and stop at four or five columns.
  5. Compare EXPLAIN indexes = 1 granule 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.
Documented sort-key rewrites (vendor measurements)
DatasetBeforeAfterResult
Stack Overflow postsORDER 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 PaidKey (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
Swipe sideways on small screens to see every column.

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.

Comparison of ClickHouse ORDER BY tuple full scan reading 489 of 489 granules versus low-cardinality primary key reading 22 of 489 granules
Same 4M-row dataset and filter: ORDER BY tuple() scans all 489 granules, while leading with a low-cardinality column prunes down to 22 granules.
Same data, same filter, two sort keys (hands-on observation, ClickHouse 26.9.2.1)
TableORDER BYGranules readRows readBytes readIndexes section in EXPLAIN
events_scantuple()489 of 4894,000,00020,000,000Absent: full scan
events_keyed(event_type, toDate(ts))22 of 489174,336871,680PrimaryKey, binary search
Swipe sideways on small screens to see every column.

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: 1
Note: Output layouts differ
The documented output above uses the box-drawn layout of the default client format. The check here printed a plan tree. Newer versions also add lines such as Search Algorithm and, in some versions, a Statistics section. Read the Parts and Granules lines; the rest is layout.
Choose the key from your real filters, put low cardinality first, round timestamps, and prove the change with granule counts.

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.

Visual comparison showing how ClickHouse Nullable(Int64) stores a hidden UInt8 mask file alongside 8-byte values versus compact UInt16 and LowCardinality(String)
Every Nullable column writes and scans a second hidden UInt8 null-mask file—auditing inferred schemas often removes pure I/O overhead.

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.

Type choices that shrink I/O
PatternCostly defaultCheaper choiceDocumented reason
Inferred integersNullable(Int64)UInt8, UInt16, UInt32 or UInt64, chosen by rangeSmallest bit-width that fits. Unsigned if no negatives.
Repeated short stringsStringLowCardinality(String)Under about 10,000 unique values use dictionary encoding. A 12-byte value becomes a 4-byte reference.
TimestampsDateTime64(6)Date, DateTime, or DateTime64(3)Use microseconds only if you need them. Date is 16 bits.
Finite setsStringEnum8 or Enum16Smaller, and it validates values at insert time.
Monotonic numbersDefault codecCODEC(Delta, Default)Used on ID and count columns in the official optimized schema.
Fixed-length textStringFixedString(N)Only when the length is truly fixed.
Swipe sideways on small screens to see every column.
Audit nulls, shrink types to the real range, and test LowCardinality instead of assuming it helps.

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.

Contrarian insight: Approximate is not the same as wrong
A dashboard that shows 1,204,331 visitors instead of 1,208,900 is not broken. A node that runs out of memory computing the exact figure is. Use exact counts for billing and audits. Use 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.

Let PREWHERE run automatically and verify it with an A/B toggle. Use approximate counts for human-facing numbers. Name your columns.

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 with sumIf(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

Memory-escape ladder: climb one rung at a time
1
Filter first
Cut rows before the GROUP BY with filters the sort key can use.
2
Aggregate higher
Group on fewer or coarser keys. Round timestamps and drop columns you do not need.
3
Sample deterministically
Use a hash of a stable key, such as cityHash64(user_id) % 10 = 0, so results stay consistent between runs.
4
Use bit-mask counters
Replace GROUP BY on strings with sumIf(1, condition) counters. Memory becomes fixed.
5
Spill to disk
Set max_bytes_before_external_group_by and max_bytes_before_external_sort. The query finishes, slower.
6
Scale up, last
Add memory only after the earlier rungs. Otherwise the next dataset will break it again.
Rungs 1 to 4 reduce the work. Rung 5 survives it. Rung 6 buys time.
Six-rung ClickHouse memory-escape ladder from filtering and deterministic sampling to bit-mask counters, disk spilling, and scaling RAM
Climb the memory-escape ladder from durable cardinality cuts (rungs 1–4) to temporary survival (rungs 5–6).

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 GB
Note: Raise the limit, or cut cardinality?
Both answers circulate, and the official knowledge-base entry itself often recommends scaling up first, which is easy on ClickHouse Cloud. In our judgment the options answer different questions. Spilling and higher limits are immediate relief that keeps a query alive. Cutting cardinality is the durable fix, and it is what Sentry reported. Do the first today and the second this week.
Tip: An upgrade can be a memory fix
On 26.10 and later, large hash tables switch to Robin Hood hashing. The vendor’s 26.10 release webinar page says this roughly halves memory for GROUP BY, uniqExact, DISTINCT and JOIN, and gives one example: uniqExact 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.

Back-of-envelope formulas
Baseline memory ā‰ˆ groups Ɨ bytes per group state
Bit-mask memory ā‰ˆ outer groups Ɨ N counters Ɨ 8 bytes
Interactive Calculator: Memory-Escape Estimator
A back-of-envelope estimate, not a measurement. Real aggregation state sizes vary by function and key type.
Press Calculate to see the estimate.
Treat every memory error as a cardinality problem first. Climb the ladder in order, and keep limits and extra RAM for the end.

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 an ANY INNER JOIN used only as an existence test with IN. 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 JOIN keeps at most one left row per key (with the default any_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.
ClickHouse JOIN optimization comparing memory-heavy ANY INNER JOIN hash table of 970 MiB against IN existence rewrite using 163 MiB
Replacing an existence-check ANY INNER JOIN with IN cut peak memory by 83% (970 MiB to 163 MiB) and ran 2.7x faster in the vendor’s benchmark.

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 JOIN when you need only one match per left row. Use IN or LEFT SEMI JOIN for 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 dictGet for repeated key lookups, or a Join table engine for a reusable in-memory lookup. A dictionary on the right side also enables the direct algorithm. The docs warn that a layout with a simple key converts the key to UInt64, 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_merge skips 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 decision table
join_algorithmUse it whenMemory profileWatch out for
directThe 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.
hashThe 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_mergeYou 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_hashThe 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_mergeMemory matters more than time.Minimal.Slow. Sorts the right table into blocks with a min-max index.
Swipe sideways on small screens to see every column.

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: 12

The 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.

Denormalize first. If you must join, rewrite existence tests to IN, keep the smaller table on the right, and trust the planner on 26.8 or later.

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.

Part-count tripwires (current defaults from the settings reference)
SettingDefaultCountsWhat happens when exceeded
parts_to_delay_insert1000Active parts in one partitionInserts are artificially slowed.
parts_to_throw_insert3000Active parts in one partitionInserts fail with a ‘too many parts’ exception.
max_parts_in_total100,000Active parts across the whole tableInserts fail with the same exception.
Swipe sideways on small screens to see every column.

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;
Anti-fix: Do not raise the part limits as your first fix
The knowledge base says raising them does not address the cause, and it advises changing them only after you have identified the cause and confirmed capacity. Raising them first delays the error, adds metadata overhead, and slows queries. Fix batching or the partition key first.

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.

Async-insert defaults (documented, current)
SettingDefaultWhat it does
async_insert_max_data_size100 MiBFlush when the buffer reaches this size.
async_insert_busy_timeout_ms200 ms (1000 ms on Cloud)Flush after this wait.
async_insert_max_query_number450Flush after this many buffered inserts.
async_insert_threads16Threads that flush buffers.
wait_for_async_insert1 (recommended)Acknowledge only after the flush. Setting 0 is fire-and-forget.
async_insert_use_adaptive_busy_timeoutOn since 24.2Timeout adapts between 50 ms and the 200/1000 ms ceiling.
Swipe sideways on small screens to see every column.

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.

Decision flowchart for ClickHouse ingest tuning comparing client-side batching of 10k-100k rows against server-side async_insert with wait_for_async_insert enabled
Batch 10k–100k rows on the client when possible; otherwise enable async_insert with wait_for_async_insert = 1 to avoid silent data loss.
Sync batching or async inserts? A decision flow
Can your client collect 10,000 to 100,000 rows and send about one insert per second?
Most pipelines with a stream processor or a queue consumer can.
↓
Yes: batch on the client
Use plain synchronous inserts. Fewer, larger parts. Nothing extra to configure.
No: many small writers
Use async_insert = 1 and keep wait_for_async_insert = 1.
↓
Tempted to set wait_for_async_insert = 0?
The docs call it very risky: silent data loss and no backpressure. Only accept this if losing rows is acceptable.
Warning: wait_for_async_insert = 0 loses data silently
In fire-and-forget mode the client gets no signal when a flush fails. Failures land in 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;
Warning: Upgrading to 26.8 can change your part counts
Since 26.8, 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.
Note: Deduplication does not mean clean reads
ReplacingMergeTree removes duplicates during background merges, not when you read. That is the core of why CDC deduplication lag happens. It also means uniqueness is a measurable dimension of data quality, so measure it instead of assuming it.

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;
Batch on the client when you can, use async inserts with wait mode on when you cannot, and treat part counts as a health metric.

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 PARTITION is 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.

Contrarian insight: Most listicles get partitioning backwards
The usual advice is to add monthly partitions to make queries fast. The vendor documentation frames partitioning as primarily data management and does not rank it among the first query-speed tools. It can help specific workloads, mainly when you filter on a partition column that is not part of the primary key. Partition for deletes and tiering first, then prove any speed benefit with granule counts.

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 ViewCount and 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 minmax skip index, then run MATERIALIZE 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). EXPLAIN showed the Skip section keeping 5 of 123 parts and 23 of 8,513 granules. This is a vendor measurement.
  • Lesson: It worked because ViewCount correlates with CreationDate, 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;
Warning: Index types changed in 26.2
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).
Skip-index chooser
Index typeFitsNote
minmaxNumeric 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_filterRare 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.
textNatural-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_v1Legacy full-text approaches.Deprecated since 26.2. Avoid in new tables.
Swipe sideways on small screens to see every column.
Partition for lifecycle and use skip indexes only when the column tracks your sort key. Prove both with EXPLAIN.

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:

  1. 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.
  2. Refreshable views re-run a query on a schedule, in REPLACE (default) or APPEND mode. 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.
ClickHouse materialized view aggregation ratio gauge showing safe under 10 percent compression versus over 70 percent storage explosion risk
Check the aggregation ratio before creating a materialized view: under 10% compresses strongly, while high-cardinality keys can multiply storage nearly 10x.

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;
Aggregation ratio
Aggregation ratio (%) = uniq(group-by columns) Ć· count() Ɨ 100
Under 10%: good compression. Over 70%: explosion risk. (Thresholds from the official community-tips page.)
Interactive Calculator: Materialized View Aggregation Ratio
Paste the two numbers from the pre-check query. Thresholds follow the official community-tips page.
Press Calculate to see the verdict.

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 vs materialized view
ProjectionMaterialized view
StorageStored 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 routingUpdated asynchronously. The optimizer picks a projection automatically.Updated synchronously on insert, or on a schedule if refreshable.
Query featuresNo JOINs or WHERE in the definition. No chaining.Supports JOINs, WHERE, and chaining.
Engines and schemaMergeTree only.Explicit schema control.
UPDATE and DELETE on the sourceIncompatible 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 queriesDo not work with FINAL.Unaffected by that limit.
Parallel replicasNot supported.Supported.
Failure handlingHandled silently.An INSERT failure can lose the view’s data.
Version noteSince 25.6, queries can filter by more than one projection.None.
Swipe sideways on small screens to see every column.

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.

Note: Lazy materialization and projections
The docs note that you may need to set query_plan_optimize_lazy_materialization = false when you are checking projection compatibility. Treat that as a diagnostic toggle, not a default.
Run the aggregation-ratio check before you create a view. Pick projections for simple, automatic speedups, and views when you need joins or control.

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 classWhat it means hereExamples in this article
Documented capabilityBehavior and defaults stated in official ClickHouse documentation or knowledge-base pages.Granule size, async-insert defaults, part-count defaults, version milestones, setting names.
Vendor measurementA 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 reportA 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 observationSomething 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.
Swipe sideways on small screens to see every column.

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:

  1. Pin the version and the thread count (max_threads).
  2. Do one warm-up run, then take the median of several runs.
  3. Alternate the order of the variants so neither benefits from running second.
  4. Turn off use_query_cache and use_query_condition_cache, or say that you left them on.
  5. 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.

Tip: Memory is money on managed clusters
On a service that bills for provisioned or autoscaled memory, bounded-memory patterns like sampling and bit-mask counters also lower cost. That is our inference, not a vendor claim, so check it against your own bill.

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.

Control the cache state when you measure, declare your method, and remember that the host operating system is part of the system.

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.

Ten mistakes, mapped to fixes
MistakeWhy it hurtsFixWhere
1. SELECT * on wide tablesEvery column is another file to read.Name only the columns you need.Layer 3
2. Nullable everywhereHidden 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 BYA 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 columnMerges are per partition, so parts pile up.Partition for lifecycle. Hundreds at most, never thousands.Partitioning
5. A skip index on every columnWithout 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 fixDelays the error, adds metadata overhead, slows queries.Batch bigger or use async inserts.Ingest
7. Scheduling OPTIMIZE FINALForces heavy merges as a routine job.Read why scheduled OPTIMIZE FINAL backfires before you automate it.Ingest
8. GROUP BY on three high-cardinality columnsMillions of aggregation states in memory.Climb the memory-escape ladder.Layer 4
9. Fire-and-forget async insertsFailed flushes lose data without telling the client.Keep wait_for_async_insert = 1.Ingest
10. Judging by averages or warm-cache rerunsHides the slow query and flatters the fix.Isolate one query. Control the caches.Diagnosis
Swipe sideways on small screens to see every column.
Most costly mistakes are defaults nobody questioned: inferred types, a convenient key, a quick setting. Question the defaults first.

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.

Seven-day ClickHouse performance tuning roadmap from query_log diagnosis and ORDER BY audit to memory, JOIN, ingest, and view checks
A 7-day ClickHouse performance tuning sprint: change one lever per day and measure before moving to the next.
Seven days, one lever per day
1
Day 1: Diagnose
Run the query-log report. Pick the one pattern with the highest total cost. Capture its three-run split and its EXPLAIN output.
2
Day 2: Audit ORDER BY
Compare your five heaviest filters with the key. Look for a high-cardinality or timestamp-first key.
3
Day 3: Audit types
Run the type audit on a subset. Find Nullable columns with zero nulls, oversized integers, and wide timestamps.
4
Day 4: Memory ladder
Take your highest-memory query and climb the ladder. Add spill settings as a safety net.
5
Day 5: JOIN pass
Rewrite existence-test joins to IN, check join sides, and confirm the algorithm with EXPLAIN.
6
Day 6: Ingest pass
Check part counts. Fix batch sizes or turn on async inserts with wait mode on.
7
Day 7: Views and monitoring
Run the aggregation-ratio check on every view. Schedule the query-log report so the next regression finds you first.

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.

Before and after, with evidence class
AreaBeforeAfterEvidence
Sort keyFull scan of about 59.8M rows.196.53K rows read.Vendor measurement, 4Ɨ faster
MemoryMillions of aggregation states.Bounded counters.Sentry-reported, memory 100x lower
JOINANY INNER JOIN: 27.101 s, 970.01 MiB.IN: 10.206 s, 162.81 MiB.Vendor measurement, 2.7Ɨ faster
Wide readsWide columns read for every candidate row.Wide columns read for surviving rows only.Vendor measurement, 219 s to 139 ms
ViewsAggregation ratio above 70%.Ratio under 10%.Official thresholds
IngestMany tiny synchronous inserts.10,000 to 100,000 rows per batch, or async with wait mode on.Documented guidance
Swipe sideways on small screens to see every column.
Tip: A 20-minute validation lab
Prove the guide on your own cluster without trusting any number here. (1) Build one table with 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.

About The Author

A Gadallh

Ahmed Gadallah is the Founder and Editor of Vertex Frontier, where he publishes research-driven articles on AI, data science, cloud computing, cybersecurity, software engineering, and emerging technologies, with a focus on technical accuracy, clarity, and practical insights.

View all articles by A Gadallh →

Was this article helpful?

5 Comments

Comments are closed.

šŸ  Home šŸ”– Saved šŸ“§ Join Us šŸ“¤ Share ā¬†ļø To Top
Read Next Apache Iceberg vs Delta Lake vs Hudi: Which Table Format Should You Choose?