ClickHouse JOIN performance: 7 fixes for slow joins

A hash join builds its right side in memory, and most slow ClickHouse joins come from forgetting that. How to diagnose yours, plus seven fixes ordered by effort.

ClickHouse JOINs are slow for one structural reason: the default hash join loads the entire right-hand table into an in-memory hash table before it processes a single row from the left, so a large, unfiltered or wide right side becomes memory pressure, a spill to disk, or a MEMORY_LIMIT_EXCEEDED error. ClickHouse’s own guide to minimizing and optimizing JOINs describes this build-then-probe shape and advises keeping joins to a minimum in high-performance workloads. Two things make it worse. Until release 24.12 the planner never swapped tables for you, so whatever you wrote on the right was the build side, and reordering across three or more tables only arrived in 25.9. And on a sharded cluster, a join between two Distributed tables can turn into one request per pair of shards. Almost every slow join traces back to a handful of patterns. Here is how to find yours, and seven fixes ordered from cheapest to most structural.

Why are ClickHouse JOINs slow?

A hash join has two phases. The build phase reads the right-hand table into a hash table keyed on the join columns. The probe phase streams the left-hand table past it. The left side can be billions of rows because it is streamed; the right side has to fit in memory, along with every right-side column the query returns.

Four things turn that design into a slow query:

  1. The right side is too big. A fact table on the right means a multi-gigabyte hash table per execution, which fails or spills past the memory limit.
  2. The plan is the query you wrote. ClickHouse historically had no cost-based join ordering. 24.12 added automatic swapping of a join’s two sides, 25.9 added reordering for many-table joins using column statistics you created by hand, and according to ClickHouse’s account of how joins got faster, those statistics are collected automatically from 26.4. On older versions, table order is your job.
  3. Nothing is cached. The JOIN reference states that each run re-executes the right-hand subquery, so a dashboard whose tiles all join the same dimension rebuilds that hash table per tile, per refresh.
  4. Distributed tables multiply the work. Covered in Fix 6.

Memory per node is the constraint that matters for joins; ClickHouse sizing for a data team of 20 covers how to budget it.

How do you find the slow JOIN?

Start with system.query_log. It records duration, rows read and memory for every query, and normalized_query_hash groups runs that differ only in literal values:

SELECT
    normalized_query_hash,
    any(query)                            AS sample_query,
    count()                               AS runs,
    countIf(exception_code = 241)         AS memory_limit_failures,
    round(avg(query_duration_ms))         AS avg_ms,
    formatReadableSize(max(memory_usage)) AS peak_memory
FROM system.query_log
WHERE event_time > now() - INTERVAL 7 DAY
  AND type IN ('QueryFinish', 'ExceptionWhileProcessing')
  AND query_kind = 'Select'
  AND query ILIKE '%JOIN%'
GROUP BY normalized_query_hash
ORDER BY max(memory_usage) DESC
LIMIT 20;

Exception code 241 is MEMORY_LIMIT_EXCEEDED, the classic signature of an oversized build side. Recent releases also record the algorithm that actually ran in a used_join_algorithms column; add it if your server has it.

Then read the plan of the worst shape:

EXPLAIN actions = 1
SELECT c.country, count() AS purchases
FROM events AS e
INNER JOIN customers AS c ON c.customer_id = e.customer_id
WHERE e.event_date >= today() - 30
GROUP BY c.country;

Check which table feeds the right (build) input of the Join step, and whether your WHERE conditions sit beneath the join or above it. Since 26.7, EXPLAIN ANALYZE also reports build and probe timings separately. Join defaults changed repeatedly in 2025 and 2026, so check yours with SELECT name, value FROM system.settings WHERE name LIKE '%join%'. To turn this evidence into a root cause with an LLM’s help, see using LLMs for query root-cause analysis.

Fix 1: Put the smaller table on the right, or confirm the planner does

The build side should be the smaller input after filtering:

SELECT c.country, count() AS purchases
FROM events AS e                -- large: streamed (probe side)
INNER JOIN customers AS c       -- small: hashed in memory (build side)
    ON c.customer_id = e.customer_id
GROUP BY c.country;

On 24.12 and later, query_plan_join_swap_table defaults to auto: the planner estimates both inputs and builds from the smaller one, whatever order you wrote (false keeps your order, true always swaps). The choice rests on estimates, so confirm it in EXPLAIN. If it builds from the wrong side, write the order you want and pin query_plan_join_swap_table = 'false' for that query.

Fix 2: Filter and trim both sides before the join

Every row reaching the build side costs memory, and so does every right-side column the query returns. ClickHouse pushes filters as deep into the plan as it can, usually below the join, but not every condition moves. When one does not, the docs suggest rewriting that side as a subquery:

SELECT c.country, count() AS purchases
FROM
(
    SELECT customer_id FROM events
    WHERE event_date >= today() - 30 AND event_type = 'purchase'
) AS e
INNER JOIN
(
    SELECT customer_id, country FROM customers
    WHERE plan = 'enterprise'
) AS c ON c.customer_id = e.customer_id
GROUP BY c.country;

Recent releases also filter the left side for you: join runtime filters (enable_join_runtime_filters, introduced in 25.10, on by default by 26.4) build a Bloom filter from the right-side keys and drop left-side rows that cannot match before the hash lookup.

Fix 3: Use IN, SEMI or ANY when you don’t need every match

Many joins exist only to filter. If no right-side column is returned, you may not need a join, and the JOIN reference notes that IN is sometimes more efficient:

SELECT customer_id, country
FROM customers
WHERE plan = 'enterprise'
  AND customer_id IN
  (
      SELECT customer_id FROM events
      WHERE event_date >= today() - 30 AND event_type = 'purchase'
  );

When you need join syntax, match the strictness to the question. LEFT SEMI JOIN keeps left rows with at least one match, without a Cartesian product, and LEFT ANTI JOIN keeps rows with none. LEFT ANY JOIN attaches at most one right row per left row; the best-practices guide notes ANY joins are faster and use less memory. The default strictness, ALL, returns every matching combination, so a one-to-many key multiplies the left side and inflates aggregates.

Fix 4: Swap dimension lookups for a dictionary

For a dimension looked up by key, a dictionary is usually fastest: loaded into memory once and refreshed on a schedule, so nothing is built per query:

CREATE DICTIONARY customers_dict
(
    customer_id UInt64,
    country     String,
    plan        String
)
PRIMARY KEY customer_id
SOURCE(CLICKHOUSE(QUERY 'SELECT customer_id, country, plan FROM customers'))
LIFETIME(MIN 300 MAX 600)
LAYOUT(HASHED());

SELECT dictGet('customers_dict', 'country', customer_id) AS country,
       count() AS purchases
FROM events
WHERE event_type = 'purchase'
GROUP BY country;

To keep join syntax, LEFT ANY JOIN customers_dict lets ClickHouse use the direct algorithm, which looks keys up instead of hashing; it supports INNER and LEFT joins on a single-column equality key.

The caveats: dictionaries do not allow duplicate keys, so a one-to-many relationship silently loses rows. They live in memory, uncompressed, on every node, and can lag the source by up to the LIFETIME window. For a missing key dictGet returns the attribute’s default; use dictGetOrNull when “missing” matters.

Fix 5: Pick the join algorithm deliberately

join_algorithm takes an ordered list, and ClickHouse uses the first algorithm that supports the query’s join kind, strictness and table engine. Since 24.12 the default is direct,parallel_hash,hash; 26.8 appended ie_join for inequality-only joins. Every option is listed in the join settings reference.

AlgorithmMemoryUse it whenWatch out for
parallel_hashRight side in RAMIt fits; the default for equality joinsMemory grows with the right side
hashRight side in RAMYou need a kind or strictness others lackSame memory profile
directKey lookups, no hash tableRight side is a dictionary or key-value engineINNER and LEFT only
grace_hashBuckets, most on diskLarge right side, bounded memorySlower; needs a spill threshold on current releases
full_sorting_mergeSorts both sides, can spillBoth tables sorted on the join keySort cost when they are not
partial_mergeLowestMemory matters more than speedSlower; RIGHT and FULL need ALL strictness
autoStarts as hashYou want a switch when memory runs outWhat ran may differ from what you asked

When both tables are sorted by the join key because it is their primary key, a sort-merge join can skip the sort step:

SELECT o.order_id, s.status
FROM orders AS o
INNER JOIN shipments AS s ON s.order_id = o.order_id
SETTINGS join_algorithm = 'full_sorting_merge';

Do not confuse caps with spilling. max_rows_in_join and max_bytes_in_join (default 0, unlimited) are hard caps that throw by default (join_overflow_mode) and never make a join spill. The current reference configures spilling through max_bytes_before_external_join and max_bytes_ratio_before_external_join, and skips grace_hash when neither is set. These settings are recent, so confirm your version has them.

Fix 6: Co-locate distributed joins, or use GLOBAL on purpose

On a sharded cluster, a plain JOIN between Distributed tables sends the query to every shard, and each shard runs the right-hand subquery itself. If that subquery reads another Distributed table, every shard queries every shard: the distributed subqueries documentation counts 10,000 elementary requests on 100 servers. The default distributed_product_mode = 'deny' refuses this with an exception.

Two shapes are correct:

  • Co-locate and join locally. Shard both tables by the join key so each key’s rows share a shard; distributed_product_mode = 'local' rewrites the subquery to the local table. Fastest, and only correct when keys really are co-located.
  • GLOBAL JOIN for a small right side. The initiating server runs the subquery once and ships the result to every shard as a temporary table. Good when the right side is small after filtering, painful when it is large.
SELECT c.country, count() AS purchases
FROM events_distributed AS e
GLOBAL INNER JOIN
(
    SELECT customer_id, country FROM customers_distributed
    WHERE plan = 'enterprise'
) AS c ON c.customer_id = e.customer_id
GROUP BY c.country;

Fix 7: Denormalize at ingest, or pre-join into a mart

The fastest join never runs at query time. The best-practices guide strongly recommends denormalization for latency-sensitive workloads, moving the work to insert time, and suggests at most three or four joins per query. Flatten attributes in the pipeline, rebuild a pre-joined mart on a schedule, or enrich rows on insert:

-- events_enriched must exist with matching columns
CREATE MATERIALIZED VIEW events_enriched_mv TO events_enriched AS
SELECT
    event_date,
    event_type,
    customer_id,
    dictGet('customers_dict', 'country', customer_id) AS country,
    dictGet('customers_dict', 'plan', customer_id)    AS plan
FROM events;

The trade-off: denormalized attributes freeze at write time. When a customer changes plan, old rows keep the old value, which is either the point-in-time answer you wanted or a bug. Materialized views vs projections in ClickHouse covers when each mechanism fits; cross-table enrichment needs a materialized view, since a projection cannot see a second table.

Two correctness traps that look like speedups

join_use_nulls. With the default 0, a LEFT JOIN fills unmatched right-side columns with the type’s default, 0 or an empty string. That avoids Nullable overhead, but WHERE c.customer_id IS NULL finds nothing on a non-Nullable key. Set it to 1 for standard SQL behaviour. Separately, NULL join keys never match; use isNotDistinctFrom in ON if they should.

ANY is not “the right row”. LEFT ANY JOIN keeps one match per left row, and which one can vary with a parallel build. Use it only when matches are unique or interchangeable.

Making join performance someone’s job

These fixes work best when join logic is written once and reused, not re-derived in every dashboard query. That is the job of a semantic layer with materialized marts. In Goni, mart models join their staging models once and materialize as table or incremental models, so dashboards and metrics read pre-joined facts rather than rebuilding the same hash table on every tile.

For diagnosis, Goni includes a browser over system.query_log and a Doctor agent that reads a slow query’s log row, its EXPLAIN output and the table’s part layout, then proposes a fix for a person to review. It is one option among several; the seven fixes above work on any ClickHouse deployment.

FAQ

Which table should be on the right side of a ClickHouse JOIN?

The smaller one, after filtering. ClickHouse builds an in-memory hash table from the right-hand input and streams the left-hand input past it. From 24.12, query_plan_join_swap_table = 'auto' lets the planner swap the sides when it estimates the right side is larger, but confirm that in EXPLAIN, and write the order yourself on older versions.

What is the default JOIN algorithm in ClickHouse?

Since 24.12, join_algorithm defaults to the list direct,parallel_hash,hash, and 26.8 appended ie_join for joins with only inequality conditions. ClickHouse uses the first algorithm in the list that supports the query, so most equality joins run as parallel_hash, while dictionary-backed right sides use direct key lookups instead of a hash table.

How do I fix “Memory limit exceeded” on a ClickHouse JOIN?

Shrink the build side first: put the smaller table on the right, filter it and trim its columns in a subquery, or replace the join with a dictionary lookup. If the right side is genuinely large, switch to a memory-bounded algorithm such as grace_hash, partial_merge or full_sorting_merge, and accept slower execution in exchange for predictable memory.

Is dictGet faster than a JOIN in ClickHouse?

For key lookups against a dimension, usually yes. A dictionary is loaded into memory ahead of time, so the query skips building a hash table, and ClickHouse’s documentation calls the dictionary-backed direct join its fastest join algorithm. The catch is that dictionaries keep one row per key, so one-to-many relationships silently lose rows.

What is the difference between JOIN and GLOBAL JOIN in ClickHouse?

On Distributed tables, a plain JOIN runs the right-hand subquery on every shard, which is only correct when both tables are sharded by the join key. GLOBAL JOIN runs the subquery once on the initiating server and sends the result to every shard as a temporary table. Use it when that right side is small after filtering.