Skip to content

Lesson 7 of 9 · 26m

Query Optimization: Read Less, Compute Less

Practical ClickHouse tuning: predicates that prune, projections and indexes that match reality, join discipline, memory limits, and reading query plans like evidence.

The fastest ClickHouse query is the one that avoids work. That sounds obvious until you watch teams spend weeks tuning memory settings for a query that scans a year of raw events to answer a seven-day question. Optimization starts with physical layout and query shape. Settings are the last 10%, not the first 90%.

Start with the estimate

EXPLAIN ESTIMATE
SELECT tenant_id, count()
FROM events
WHERE event_time >= now() - INTERVAL 30 DAY
GROUP BY tenant_id;

Look at rows and parts scanned. Then compare that to the time range you actually need. If the filter cannot use the sorting key or partition key, ClickHouse will cheerfully scan far more than intuition suggests.

Common pruning mistakes include wrapping the filter column in a function:

-- worse for pruning
WHERE toDate(event_time) = today()

-- better
WHERE event_time >= today()
  AND event_time < today() + 1

The first form asks the database to evaluate a function before it knows whether a granule can be skipped. The second preserves a direct range predicate.

Match the sorting key to the question

If the table is ordered by (tenant_id, event_time), a tenant-plus-time query is beautiful. A query filtering only on country has no help from the primary index. You can sometimes add a data-skipping index for selective secondary predicates:

ALTER TABLE events
ADD INDEX country_idx country TYPE set(100) GRANULARITY 4;

Skipping indexes are not free B-trees. They help when they can eliminate granules, and they cost storage and insert work. minmax, set, and bloom-filter indexes solve different shapes of problem. Measure with real queries; do not sprinkle them like seasoning.

Joins: keep one side small

ClickHouse joins are strongest when the right side is small enough to build an efficient hash table. Dimension tables are fine. Giant fact-to-fact joins are often a sign the data should have been denormalized at ingestion time. If every dashboard joins events to a huge user snapshot, ask whether the needed user attributes should have been copied into the event row.

Memory is a hard boundary

Aggregation state, join hash tables, and sorting all consume memory. max_memory_usage and related settings are guardrails, not performance tuning dials. A query that only passes after you raise limits to absurdity is telling you the algorithm or data volume is wrong.

Useful interpretations: high memory with GROUP BY user_id means enormous cardinality; high memory in a join often means the right table is not small; high memory in ORDER BY means you are sorting too much before limiting.

Prewhere and column selection matter

PREWHERE can reduce data read for selective filters before heavier columns are decoded. ClickHouse often chooses this automatically, but understanding it helps when analyzing plans. Selecting only required columns is even more fundamental. A dashboard that fetches raw JSON properties and then ignores them is burning I/O for nothing.

Field notes

  • Compare system.query_log rows by read_rows, read_bytes, memory_usage, and query_duration_ms. Duration alone hides the cause.
  • FINAL, GROUP BY over high cardinality, distributed fan-out, and large joins are the usual suspects when memory spikes.
  • A subquery is not automatically slow, but hiding scan volume inside layers of SQL makes reviews harder.
  • Time filters should be explicit in every analytic query. "Oops, no time bounds" is the most expensive typo in analytics.
  • Optimize the top few queries by total cluster cost, not the slowest query someone happened to notice once.

Was this lesson helpful?

Sign in to rate