ClickHouse dictionary vs JOIN vs IN in 26.11: three lookups that now end in the same key set

In ClickHouse 26.11 a JOIN prunes granules with an exact IN set of up to 10,000 keys, and dictGet in WHERE turns into IN. A hashed dictionary costs 32–64 B per key per attribute.

The usual advice on ClickHouse lookups has three parts: turn small dimension tables into dictionaries and call dictGet instead of joining, use IN (subquery) instead of a JOIN when you only need to filter, because IN can use the primary key and a JOIN can’t, and never put dictGet in WHERE, because it “evaluates row by row with no index support” (that quote is from ClickHouse’s current dictionary best-practices page).

Two of those three rules are out of date in ClickHouse 26.11. Since 26.10 a hash JOIN sends its build-side keys to the left table as a runtime filter. With up to 10,000 keys that filter is an exact IN set, and it prunes primary-key granules just like a hand-written IN. Since 25.12, WHERE dictGet(d, 'attr', key) = 'x' is rewritten to key IN (…), which can use the left table’s primary key too. The three forms now share the same machinery. What still differs is when the lookup structure is built (once per dictionary LIFETIME, or once per query) and how much memory it takes. For a hashed dictionary that is 32 to 64 bytes per key for every attribute.

This is day 14 of the ClickHouse series. Everything below is read from the source at tag v26.11.1.2942-stable, the setting docs in Settings.cpp, the changelog, and measurements published by ClickHouse. Nothing was benchmarked for this post. The memory numbers are arithmetic from the data structures, and they are labelled as such.

The short answer

JOIN with a table JOIN with a dictionary dictGet IN (subquery)
Built every query (hash table) once per LIFETIME, then reused once per LIFETIME every query (set)
Memory query memory, freed after resident on every server resident on every server query memory, freed after
Can prune the left table’s granules yes, by runtime filter (26.10+) no in WHERE, by rewrite to IN (25.12+) yes, by primary key
Spills to disk at 50% of memory (26.5+) no (dictionary must fit) no at 50% of memory (26.10+)
Range lookups (BETWEEN from AND to) yes not as a direct join range_hashed layout no
Four ways to write a lookup, and what ClickHouse 26.11 builds for eachJOIN dictionarydirect joinno hash table: each left block is looked up in thedictionary's memory; not for range_hashedJOIN tablehash join + runtime filter≤ 10,000 build keys: exact IN set prunes left granulesmore: min/max range + 512 KiB Bloom filterWHERE dictGet(…) = 'x'inverse lookup (25.12+)rewritten to key IN (keys whose attribute = 'x'),so the left table's primary key can be usedWHERE key IN (subquery)set, built once per queryprimary key index on the left; spills to diskat 50% of memory (26.10+), then no indexRows 2–4 end in the same thing: a set of keys checked against the left table's primary key.
Read from the 26.11 source: PlannerJoinsLogical.cpp, InverseDictionaryLookupPass.h and the defaults in Settings.cpp. Simplified.

The trade-off in one published example

The ClickHouse dictionary guide has the clearest example of the trade-off. It finds the most controversial SQL post in the Stack Overflow dataset twice: once with a JOIN against an aggregated votes subquery, and once with a hashed dictionary of up- and down-votes per post. The docs ran it on a ClickHouse Cloud node with 64 GB of RAM and don’t give the server version:

JOIN dictGet
Query time 1.283 s 0.551 s
Rows read 418.44 million 119.64 million
Peak query memory 3.18 GiB 552.26 MiB
One-time cost none 36.1 s to load, 4.00 GiB resident

The dictionary query is 2.3× faster and uses a sixth of the query memory, because the vote counts are already aggregated and sitting in memory. But that memory never goes away: the dictionary holds 4.00 GiB on every server (in self-managed clusters you create it on every node), and it has to be reloaded on every LIFETIME refresh. A query that runs once an hour is better off with the JOIN. A dashboard that runs it every few seconds is better off with the dictionary.

ClickHouse’s own larger benchmark (1.4 billion fact rows, 17 queries, ClickHouse Cloud, version not given) points the same way. Replacing dimension-table joins with dictionaries cut the total runtime from 251.05 to 133.78 s on 2 nodes and from 169.19 to 47.31 s on 8 nodes. The biggest single gain was 6.6× (Q10, 89.44 → 13.84 s on 8 nodes). Several of those joins were range joins (order_date BETWEEN from_date AND to_date), which a range_hashed dictionary answers directly and a hash join can only handle by filtering after an equality match.

Why that dictionary is exactly 4.00 GiB

4.00 GiB is exactly 2^32 bytes, and the source explains why. In 26.11 a hashed dictionary with a UInt64 key keeps one hash table per attribute, each mapping key → value (HashedDictionaryMapType in HashedDictionaryCollectionType.h: a HashMap<UInt64, Value>). A cell holds the 8-byte key and the value, padded to 16 bytes for any value up to 8 bytes. The table is a power of two in size and at most max_load_factor full (default 0.5, allowed 0.5 to 0.99). During loading it reserves room for every block it reads.

So votes_dict (key PostId, attributes UpVotes UInt32 and DownVotes UInt32) is two tables of 2^27 cells × 16 bytes = 2 × 2 GiB = 4 GiB. 2^27 cells at half fill is right for anything between 33.6 and 67.1 million keys, and the docs’ posts table has 59.8 million rows. Each key is stored twice, once per attribute, and the table is between a quarter and half full.

hashed_array stores the key once: one HashMap<UInt64, size_t> from key to row number (16-byte cells), plus one plain array per attribute (HashedArrayDictionary.h). For votes_dict that would be 2 GiB for the key table plus 8 bytes per key for the two arrays, roughly 2.3 to 3 GiB depending on how much spare room the arrays keep after growing. That is arithmetic, not a measurement.

Memory per key, simple UInt64 key, k UInt32 attributes (bytes)1 attributehashed: 32–64 B/key32–64hashed_array: 36–68 B/key36–68flat, dense keys: 4 B/key4 (flat, dense keys)2 attributeshashed: 64–128 B/key64–128hashed_array: 40–72 B/key40–72flat, dense keys: 8 B/key8 (flat, dense keys)4 attributeshashed: 128–256 B/key128–256hashed_array: 48–80 B/key48–80flat, dense keys: 16 B/key16 (flat, dense keys)8 attributeshashed: 256–512 B/key256–512hashed_array: 64–96 B/key64–96flat, dense keys: 32 B/key32 (flat, dense keys)hashedhashed_arraysolid = table half full, light = quarter fullArithmetic from 26.11 data structures; max_load_factor 0.5, one shard; strings add their bytes
Computed from HashedDictionaryCollectionType.h (hashed: one HashMap<UInt64, V> per attribute, 16-byte cells), HashedArrayDictionary.h (one key → index map plus one array per attribute) and FlatDictionary. Not measured.

The general rule, for a UInt64 key and k attributes of up to 8 bytes each, with c = 2 to 4 cells per key:

Layout Bytes per key k = 1 k = 2 k = 8
hashed 16 · c · k 32–64 64–128 256–512
hashed_array 16 · c + Σ value sizes 36–68 40–72 64–96
flat (dense keys) Σ value sizes × (max key + 1) ÷ keys 4 8 32

(The numbers in the table are for UInt32 values.) So hashed_array uses less memory as soon as there are two attributes, which matches the best-practices page’s advice to make it the default. hashed is only smaller with a single attribute, and then only by 4 bytes per key. flat is the cheapest by far when keys are dense integers. It is sized by the largest key, not the number of keys, and stops at max_array_size = 500,000 unless you raise it (FlatDictionary.cpp). Keys 1 and 500,000 cost the same as all 500,000 keys.

Two more details from the same file. sparse_hashed uses PackedHashMap, with unpadded cells of 8 + value bytes (12 for a UInt32), for values up to 8 bytes, and Google’s sparse_hash_map for larger values. A comment in the code gives the memory for 10^9 elements of 16-byte pairs: 35 GiB with HashMap, 26 GiB with sparse_hash_map, 22 GiB with PackedHashMap. And a String attribute in hashed is a 24-byte cell (key plus a 16-byte pointer and length) with the characters stored in an arena, so long strings cost their length on top of that.

system.dictionaries.bytes_allocated shows the real number. Check it before you add an attribute “just in case”: in hashed, each extra attribute costs another full hash table.

JOIN with a dictionary: a direct join, no hash table

You don’t have to rewrite a join as dictGet to get dictionary speed. If the right side of a JOIN is a Dictionary table, the default join_algorithm (direct,hash,ie_join in 26.11) starts with direct. tryDirectJoin in PlannerJoins.cpp then looks up each block of left rows in the dictionary’s own memory, with no hash table built for the query. The conditions are strict:

  • INNER ALL, or LEFT with ANY, ALL, SEMI or ANTI.
  • Exactly one equality key, and it must be the dictionary’s primary key, with the same type once Nullable and LowCardinality are stripped. A JOIN … USING that casts the key to a common supertype doesn’t qualify.
  • No other ON conditions, not even filters on one side.
  • Not a range dictionary: PlannerJoinsLogical.cpp explicitly excludes range_hashed. Use dictGet(dict, attr, key, date) for those.

If any condition fails, the planner moves on to hash and builds a hash table from the dictionary’s contents for that query, which loses most of the benefit. EXPLAIN shows which one you got.

Since 25.12 there is also a direct join into ordinary MergeTree tables (#89920), but only if you ask for it: tryMakeDirectJoinWithMergeTree in PlannerJoinTree.cpp runs only when join_algorithm is exactly 'direct', for INNER or LEFT joins with ALL, SEMI or ANTI strictness and one equality key. For each block of left rows it builds an IN set of that block’s keys and runs a filtered read of the right table (DirectJoinMergeTreeEntity.cpp). The settings docs say this is fast when the key is in the right table’s primary key, and otherwise “performs full scans of the right table for each left table block”. It’s a nested-loop join that uses the right table’s index, useful when a small left side looks up a few rows in a huge table.

IN: one set per query, and the primary key on the left

x IN (SELECT …) builds a hash set once per query. For a UInt64 key it is a HashSet<UInt64> with 8-byte cells, at most half full (SetVariants.h). With use_index_for_in_with_subqueries = 1 (the default), the set also keeps its elements as columns so that index analysis can use them, and the left table reads only the primary-key granules that can contain those keys. use_index_for_in_with_subqueries_max_values (0, no limit) can cap that.

26.10 added something the old advice doesn’t cover: sets spill to disk. With max_bytes_ratio_before_external_set = 0.5 (default since 26.10, #123860), a set built from a subquery or a table goes to disk once query memory passes half the available memory, if it is at least 16 MiB. A set on disk keeps a Bloom filter in memory, about 1 byte per key, so that ~97% of lookups for keys that aren’t in the set skip the disk. It has a 128 MiB budget, which covers about 130 million keys (max_bytes_for_external_set_bloom_filter). There is a catch in the IN docs: “A set written to disk while it is built cannot be used by the primary key or data skipping indexes.” So a huge IN doesn’t fail any more, but it reads more of the left table.

JOIN with a table: the runtime filter is an IN now

The rule “use IN instead of JOIN because only IN uses the index” changed in two steps. Since 26.2, enable_join_runtime_filters = 1: a hash join collects the keys of its build side and filters the probe side with them before the join. Since 26.10, enable_join_runtime_filters_index_analysis = 1 (#121859) uses that filter to skip granules of the probe side while reading. The setting’s description in Settings.cpp gives the details:

  • Up to join_runtime_filter_exact_values_limit = 10,000 distinct keys, the filter keeps the exact values, and “the pruning predicate is an IN set of them”. Above that it becomes a Bloom filter (512 KiB, 3 hash functions), and pruning uses only the min/max key range, “this has a lower pruning power”.
  • Pruning works only when the join key is a primary-key column of the probe side, or covered by a minmax, set or bloom_filter skip index.
  • The filter applies to INNER joins, SEMI/ANTI joins and RIGHT joins (joinRuntimeFilter.cpp). It doesn’t apply to a plain LEFT JOIN, which has to keep every left row anyway.
  • It is skipped when the probe side is estimated at 1,000 rows or fewer, turned off for 30 blocks when more than 70% of rows pass, and not used for FINAL reads.

So SELECT … FROM events e JOIN users u ON e.user_id = u.id WHERE u.country = 'NZ' on 26.10+ reads only the events granules that can hold those users, if user_id leads events’ ORDER BY and fewer than 10,000 users match. With 50,000 matching users the filter switches to a Bloom filter and a min/max range. If those ids are spread over the whole id range, almost nothing is skipped, while e.user_id IN (SELECT id FROM users WHERE country = 'NZ') still prunes with the exact set. The limit is a setting, so raising join_runtime_filter_exact_values_limit for such a query is the other option. No published measurement says where a larger exact set stops paying off, so test it on your own data.

dictGet in WHERE: rewritten to IN since 25.12

The best-practices page warns against WHERE dictGet('dict', 'elevation', id) > 1800 because it can’t use an index. Since 25.12 that is no longer true for most such predicates. optimize_inverse_dictionary_lookup (default true since 25.12, #88971, InverseDictionaryLookupPass) rewrites

WHERE dictGet('dict', 'attr', key) = 'x'
-- into
WHERE key IN (SELECT key FROM dictionary('dict') WHERE attr = 'x')

The rewrite handles =, !=, <, <=, >, >=, LIKE, ILIKE, their negations, and IN lists. Since 26.7, a constant equality is folded straight into a key list with dictGetKeys instead of a subquery (#91164). Because the result is an IN, it uses the left table’s primary key when key is in it. The pass leaves the query alone when the rewrite would change the result:

  • the attribute is Nullable (a stored NULL behaves differently in dictGet and IN);
  • the comparison is true for the attribute’s DEFAULT: dictGet(…) = '' with default '' also matches keys that are missing from the dictionary, and the rewrite can’t see those;
  • dictGetOrDefault, a non-constant dictionary or attribute name, or a layout other than flat, hashed, hashed_array, sparse_hashed and their complex-key versions (so not range_hashed, cache, ssd_cache or direct);
  • keys of type Variant, Dynamic or JSON (excluded since 26.10).

The elevation > 1800 example qualifies (with default 0, 0 > 1800 is false), so on 25.12+ it runs as an IN. Check with EXPLAIN QUERY TREE or EXPLAIN indexes = 1.

Which one to use

Situation Use
Enrich every row of a big scan with attributes of a small, stable table, many times a day dictionary (dictGet or JOIN against it); hashed_array from two attributes on, flat for dense ids under 500,000
Same, but the lookup runs rarely or the table changes every minute plain JOIN: the hash table lives only for the query
Filter a big table by keys from a small selection JOIN or IN, both prune via the primary key on 26.10+; prefer IN when the selection has more than 10,000 keys
Filter by an attribute of a dimension WHERE dictGet(…) = 'x' is fine on 25.12+ if the attribute isn’t Nullable
Time-versioned dimension (valid_from/valid_to) range_hashed dictionary with dictGet(…, key, date)
Tiny left side, huge right table sorted by the key join_algorithm = 'direct' against MergeTree (25.12+)
Dimension too big to keep on every server JOIN (spills at 50%) or IN (spills at 50%, then no index); not cache dictionaries on insert paths

FAQ

Is a ClickHouse dictionary faster than a JOIN? For repeated lookups into a small, stable table, yes: the lookup structure is built once, not per query. ClickHouse published 2.3× on the Stack Overflow example in its docs and up to 6.6× in its coffee-shop benchmark. The price is memory on every server, all the time, plus reloads on each LIFETIME.

How much memory does a ClickHouse dictionary use? For a hashed layout with a UInt64 key: 32 to 64 bytes per key for each attribute up to 8 bytes, because every attribute has its own hash table. hashed_array stores the key once (32 to 64 bytes) plus the value sizes. system.dictionaries.bytes_allocated shows the real figure.

Does IN use the primary key index in ClickHouse? Yes, when the left side is a primary-key column (or covered by a skip index) and the right side is a constant list or a subquery (use_index_for_in_with_subqueries = 1). A set that was spilled to disk while it was built (26.10+) can’t be used by the index.

Does a JOIN use the primary key in ClickHouse? Since 26.10, for inner, semi, anti and right joins, the runtime filter prunes granules of the probe side when the join key is in its primary key. It does that exactly for up to 10,000 build-side keys and by min/max range above that.

Can I put dictGet in WHERE? On 25.12 and later, comparisons of dictGet with a constant are rewritten to key IN (…) and can use the index, unless the attribute is Nullable or the comparison also matches the attribute’s default value.

Tomorrow, day 15: materialized views and what each one adds to an insert.