ClickHouse count distinct: uniqCombined can't count past 6.2 billion, and what 26.11 changes
ClickHouse uniqCombined over numbers never returns more than 6.2 billion. Which uniq function to pick, what each state costs, and 26.11's faster count(DISTINCT).
ClickHouse has six ways to count distinct values: count(DISTINCT x), uniqExact, uniq, uniqCombined, uniqCombined64 and uniqHLL12. Most guides compare them on a million rows, where they all look fine. The differences show up at the other end of the scale, and one of them is a hard limit: uniqCombined over a numeric column can never return more than about 6.2 billion, however many distinct values there are. Raising its precision doesn’t help. The ClickHouse docs show the effect themselves: on numbers(1e10), ten billion distinct numbers, uniqCombined returns 5,545,308,725.
That number can be explained from the source and reproduced with arithmetic to within 0.05%, which is what most of this post does. The rest covers what changed this autumn: uniq stopped returning garbage above 30 billion in 26.10, and 26.11 (released 2026-11-24) made exact count(DISTINCT) up to 6 times faster with 2 to 4 times less memory.
This is day 12 of the ClickHouse series (ReplacingMergeTree, announced for day 11, moves to a post of its own). Everything below comes from the source at tags v26.10.2.103-stable and v26.11.1.2942-stable, the ClickHouse docs and changelog, and measurements published in ClickHouse pull requests. The error and memory tables are arithmetic on that code, not benchmarks.
The short answer
| Function | What it keeps per state | Max state size | Typical error | Breaks down at |
|---|---|---|---|---|
count(DISTINCT x) = uniqExact |
every distinct value (String: a 16-byte hash) | unbounded | exact | memory |
uniq |
a sample of up to 65,536 32-bit hashes (+ a 64-bit sample since 26.10) | 512 KiB (+256 KiB) | ~0.6% | ~30 billion before 26.10; trillions after |
uniqCombined (numbers) |
array → hash set → HyperLogLog, 32-bit hash | 80 KiB | 0.29% | ~1 billion; ceiling 6.2 billion |
uniqCombined (String) |
same, 64-bit hash | 96 KiB | 0.29% | no practical limit |
uniqCombined64 |
same, 64-bit hash for all types | 96 KiB | 0.29% | no practical limit |
uniqHLL12 |
HyperLogLog with 4,096 cells, 32-bit hash | 2.5 KiB | 1.6% | ~1 billion; ceiling 6.2 billion |
If you remember one rule: for approximate counts of anything that could reach a billion distinct values, use uniqCombined64. It costs 16 KiB more per state than uniqCombined and has no ceiling. For exact counts, upgrade to 26.11 before you rewrite queries.
Where the 6.2 billion ceiling comes from
HyperLogLog splits hashes into m = 2^p buckets. The first p bits of a hash choose the bucket; each bucket remembers the longest run of leading zeros (the “rank”) it has seen in the remaining bits. Many distinct values make long runs likely, so the ranks grow with the count, and the estimate is a harmonic mean of 2^rank over all buckets.
With a 32-bit hash, the remaining bits run out. In HyperLogLogCounter.h, max_rank = sizeof(HashValueType) * 8 - precision + 1: with uniqCombined’s default precision 17, a bucket’s rank can never exceed 32 − 17 + 1 = 16. When every bucket is at 16, the formula alpha_m · m² / Σ 2^-rank gives its largest possible value:
alpha_m · m · 2^(33 − p) = 0.7213 · 2^33 ≈ 6,195,868,816
The precision cancels out. uniqCombined(12), uniqCombined(20) and uniqHLL12 all have the same ceiling, because a bigger m leaves fewer bits for the rank. Only a wider hash moves it.
Two more details from the same file make the curve below. Above 2^32 / 30 (about 143 million), fixRawEstimate returns the raw estimate with no correction at all. And the classic large-range correction from the original HyperLogLog paper, for 32-bit hashes filling up, is not there. So as the count approaches 2^32 the estimate falls further and further behind, then flattens at 6.2 billion.
You can compute the expected estimate directly. Spread n hashes over 131,072 buckets, take the probability that a bucket’s maximum rank is r ((1 − 2^-r)^k for k = n / m hashes per bucket, capped at rank 16), and put the expected 2^-rank into the formula. With 131,072 buckets the average is very stable, so the expected value is what you get to within the normal 0.3% noise:
| True distinct values | Expected uniqCombined(number) |
Error |
|---|---|---|
| 100 million | 100.1 million | +0.1% |
| 500 million | 498.6 million | −0.3% |
| 1 billion | 988 million | −1.2% |
| 2 billion | 1.91 billion | −4.3% |
| 4.29 billion (2^32) | 3.61 billion | −16% |
| 10 billion | 5,547,815,133 | −44.5% |
| 30 billion | 6.19 billion | −79% |
| 100 billion | 6.196 billion | −94% |
The 10-billion row predicts 5,547,815,133. The uniqCombined64 docs page shows SELECT uniqCombined(number) FROM numbers(1e10) returning 5,545,308,725, a difference of 0.05%. On the same page uniqCombined64 returns 9,998,568,925 (−0.01%).
The uniqCombined docs warn that “the error will raise quickly after a few tens of billions of distinct values”. The table says the trouble starts earlier: the systematic error is already −1.2% at one billion, four times the function’s normal 0.29% noise, and −4.3% at two billion. A daily-active-users count won’t get there. A count of distinct event IDs, sessions or URLs over a year of data can.
Two exceptions in AggregateFunctionUniqCombined.h matter in practice:
- String and IPv6 arguments get a 64-bit hash even in plain
uniqCombined(KeyisUInt64for them, and the HyperLogLog’s hash type follows the key).uniqCombined(url)has no ceiling;uniqCombined(user_id)does. uniqHLL12uses a 32-bit hash for every type, strings included. Its docs say error grows “starting from 100M” and it is “very inaccurate” for 1B+; the ceiling is the same 6.2 billion. The docs also say not to use it.
uniq: fixed above 2 billion in 26.10
uniq works differently. It is an adaptive sample (the BJKST algorithm, per the comment in UniquesHashSet.h): it keeps 32-bit hashes in a hash table, and whenever it holds more than 65,536 of them it drops every hash not divisible by 2, then 4, then 8. The estimate is the sample size times 2^skip_degree, plus a correction for 32-bit collisions. The table can grow to 2^17 cells of 4 bytes: 512 KiB per state.
The collision correction is 2^32 · (log 2^32 − log(2^32 − res)). Once the estimate reaches 2^32 that is the log of a non-positive number. PR #115393 (by Alexey Milovidov, in 26.10, released 2026-10-22) describes the result before the fix: uniq returned 18446743978444128518 above about thirty billion, and the estimate degraded well before that.
The fix keeps the old 32-bit sample bit for bit and adds a second, heavily thinned sample of full 64-bit hashes: only one hash in 262,144 enters it, it is capped at 16,384 values (256 KiB), and size() switches to it once it holds 8,192 values, at about two billion elements. Results the PR reports:
| Query | Result | Error |
|---|---|---|
uniq(number) FROM numbers_mt(2e9) |
2,006,192,184 | +0.31% (32-bit sample) |
numbers_mt(4e9) |
4,028,331,215 | +0.71% (64-bit sample) |
numbers_mt(5e10) |
50,267,749,176 | +0.54% (was 18446743978444128518) |
numbers_mt(1e11) |
99,360,630,405 | −0.64% |
numbers_mt(1e12) |
1,003,779,179,926 | +0.38% |
The catch is in stored states. The 64-bit sample has to be fed from the first insert, so a state written by an older version can’t get one later. The PR versions the state: a column you create on 26.10+ as AggregateFunction(uniq, UInt64) is pinned to the new version 1 (it shows up as AggregateFunction(1, uniq, UInt64) in the table metadata), while tables that already existed keep version 0. An AggregatingMergeTree rollup created before 26.10 keeps the old 32-bit uniq forever, now clamped at about 9.5 × 10^10 instead of garbage. If such a rollup can pass two billion distinct values per row, you need a new column or table and a re-aggregation from raw data.
What each state costs in memory
The approximate functions bound their state; uniqExact doesn’t. These are per-state sizes from the source (the HyperLogLog registers are packed: 5 bits per bucket for a 32-bit hash, 6 for a 64-bit one, per RankWidth in HyperLogLogCounter.h):
| Function | Small sets | Medium | Large (fixed) |
|---|---|---|---|
uniqExact(UInt64) |
16 inline cells | hash set, ≤50% full, grows ×4 | 16-64 B per distinct value, per thread |
uniqExact(String) |
same, keys are 16-byte SipHash128 | 32-128 B per distinct value | |
uniq |
16 inline cells | table doubles | 512 KiB (+ up to 256 KiB 64-bit sample) |
uniqCombined (numbers) |
array of 16 | hash set ≤ 8,192 values (~64 KiB) | 80 KiB (2^17 × 5 bits) |
uniqCombined64 / on String |
array of 16 | hash set ≤ 4,096 values (~64 KiB) | 96 KiB (2^17 × 6 bits) |
uniqHLL12 |
array of 16 | none | 2.5 KiB (2^12 × 5 bits) |
The uniqCombined hash-set limit comes from the template argument K − 5 + (sizeof(Key) == sizeof(UInt32)): the code switches to HyperLogLog when the hash set would get as big as the registers, which is also why the docs’ “96 KiB (2^17 cells, 6 bits each)” is exact for strings and uniqCombined64 but rounds up for numeric uniqCombined, which needs 80 KiB.
Two practical consequences:
- In a
GROUP BYwith millions of small groups, approximation doesn’t save memory. Every function starts with about 16 values held inline, so a group with 10 distinct values costs roughly the same in all of them.uniqCombinedpulls ahead only for groups with thousands of distinct values, whereuniqExactkeeps growing anduniqCombinedstops at 80-96 KiB. - One huge
uniqExactis the expensive case. A billion distinctUInt64values need at least 16 GB of hash table, per thread, before the threads’ sets are merged. That is the case 26.11 changed.
What 26.11 changes for count(DISTINCT)
count(DISTINCT x) runs uniqExact by default (setting count_distinct_implementation = 'uniqExact'). 26.11 has a long list of uniqExact changes in its changelog; the biggest is radix partitioning for a single uniqExact without GROUP BY (PR #123552, follow-up #127252, by Raúl Marín).
Before, every thread built its own hash set and the sets were merged at the end. Once the sets outgrow the CPU caches, both the inserts and the merge wait on cache misses, and a value seen by several threads is stored several times. Now each thread starts with a small set as before, and if it would outgrow 1 MiB the thread switches to routing values by the top bits of their hash into per-bucket buffers. When all threads are done, one set per bucket is built in parallel, small enough to stay in cache, and the answer is the sum of the bucket sizes. Nothing has to be merged, and each value is stored once.
The PR’s measurements on ClickBench hits (100M rows, AMD Ryzen 9 7950X3D, 8 cores / 16 threads, median of 7 hot runs):
| Query (16 threads) | Before | 26.11 | Speedup | Peak memory |
|---|---|---|---|---|
count(DISTINCT UserID) (Q4) |
0.135 s | 0.049 s | 2.8× | 1.01 GiB → 285 MiB |
count(DISTINCT SearchPhrase) (Q5) |
0.249 s | 0.143 s | 1.7× | 625 MiB → 447 MiB |
count(DISTINCT WatchID) |
0.651 s | 0.106 s | 6.1× | 3.95 GiB → 1.02 GiB |
count(DISTINCT URL) |
1.458 s | 0.798 s | 1.8× | 2.08 GiB → 1.94 GiB |
count(DISTINCT ClientIP) |
0.088 s | 0.041 s | 2.1× | 385 MiB → 152 MiB |
optimize_uniq_exact_radix_partitioning), not measured here.What to know before you count on it:
- It applies only to a single-argument
uniqExact/count(DISTINCT)withoutGROUP BY, finalized on the same server, for numbers up to 64 bits, dates,Enum,IPv4,IPv6,UUID, 128-bit integers,String,FixedStringandNullableof them (settingoptimize_uniq_exact_radix_partitioning, on by default). A distributed query that ships states to the initiator doesn’t take this path. - It can now spill. Keyless
uniqExactcouldn’t spill to disk before, because withoutGROUP BYthere was no two-level form. Withmax_bytes_before_external_group_byset, each thread writes its deduplicated keys to its own temporary file (#127252). - A known slow case: medium-cardinality data with many repeats (
number % 250000over 50M rows) is up to 15% slower on the first run and uses up to 3× the memory, per the PR. Repeated runs use statistics from the first run to choose bucket counts and modes. count_distinct_optimizationis now obsolete (#129307). It rewrotecount(DISTINCT x)into aGROUP BY xsubquery; the radix path made that unnecessary, and the setting now has no effect.
Also in 26.11, for the GROUP BY case: merging large uniqExact states per key is parallelized, about 3× faster on ClickBench Q8/Q9 on many-core machines (#117153); uniqExact over one String argument with GROUP BY is up to 2.7× faster (#129490); and with optimize_aggregation_in_order = 1 (off by default), a keyless uniqExact(x) over a table sorted by x counts in table order without holding the values in memory (#129508).
Which one to use
| You need | Use | Why |
|---|---|---|
An exact count, no GROUP BY |
count(DISTINCT x) on 26.11+ |
radix path: 2-4× less memory than before |
| An exact count per group | uniqExact, check memory |
16+ bytes per distinct value per thread |
| An approximate count, could pass 1 billion | uniqCombined64 |
64-bit hash, no ceiling, 96 KiB |
| An approximate count of strings | uniqCombined |
strings already get a 64-bit hash |
| An approximate count of numbers, surely < 500 million | uniqCombined |
80 KiB, 0.29%; −0.3% bias at 500M |
Rollup states in AggregatingMergeTree |
uniqCombined64State |
small fixed states, merges are exact unions |
Compatibility with existing uniq states |
uniq, on a table created on 26.10+ |
version 1 state carries the 64-bit sample |
uniqHLL12 |
nothing | its own docs say don’t |
Both uniqCombined and uniqCombined64 are deterministic: the result doesn’t depend on how rows are split across threads or shards, per their docs. HyperLogLog states merge by taking the per-bucket maximum, so merging rollups adds no error beyond what one big state would have.
FAQ
Is count(DISTINCT) exact in ClickHouse?
Yes, by default. count_distinct_implementation defaults to uniqExact. You can set it to uniqCombined64 or another uniq* function to make every count(DISTINCT) approximate.
What is the error of uniqCombined?
About 1.04/√(2^p): 0.29% at the default precision 17, 0.81% at 14, 0.10% at 20. On numeric columns add a systematic undercount past ~500 million distinct values: −1.2% at one billion, −44% at ten billion.
Does a higher HLL_precision fix uniqCombined at large counts?
No. The ceiling is 0.7213 × 2^33 ≈ 6.2 billion for every precision, because a larger bucket count leaves fewer hash bits for the rank. Use uniqCombined64.
Is uniq or uniqCombined more accurate?
uniqCombined at the default precision: 0.29% standard error versus about 0.6% for uniq, with 80-96 KiB instead of 512 KiB.
Why did uniq return 18446743978444128518?
Above about 30 billion distinct values the 32-bit collision correction took the log of a non-positive number. Fixed in 26.10 (#115393) for states created on 26.10+; older stored states are clamped at about 9.5 × 10^10.
How much memory does count(DISTINCT) use?
At least 16 bytes per distinct UInt64 and 32 per distinct String per thread with the ordinary hash sets. In 26.11 the keyless case uses 2-4× less: 285 MiB instead of 1.01 GiB for ClickBench’s UserID in the PR’s run.
Tomorrow, day 13: JOIN algorithms, and when hash, parallel_hash, grace_hash and full_sorting_merge win.