Skip to main content
Use uniq when an approximate answer is acceptable, and uniqExact when you need the exact number. COUNT(DISTINCT x) is the same as uniqExact(x) by default. The other functions trade memory, accuracy and CPU time differently and cover special cases.

The functions at a glance

Compare the results

The following query counts 300000 distinct values among 1000000 rows with every function:

Why the size of the state matters

Each function keeps a state for every group of a GROUP BY. Consider a query like this:
There can be millions of distinct URLs, and most of them are visited by only one or two users. Allocating a full HyperLogLog for every URL (about 2.5 KB in uniqHLL12, and 80 to 96 KiB with the default precision of uniqCombined) would waste most of the memory. This is why the approximate functions in ClickHouse are combined data structures: uniq, uniqCombined and uniqHLL12 start with a small array or hash table and switch to the larger structure only when a group collects enough values. The state is also what is stored in a column of the AggregateFunction type (for example, in an AggregatingMergeTree table) and what is sent between servers in a distributed query. The following query shows the size in bytes of the serialized state of each function for 2, 100, 10000 and 1000000 distinct UInt32 values:
For a group with two values, every state is small (9 to 33 bytes). As the number of distinct values grows, the state of uniqExact grows linearly (4 bytes for every UInt32 value), while the states of the approximate functions stay bounded. The state of uniqUpTo(10) shrinks to one byte once a group has more than 10 values. The state of groupBitmap is very small here because the values are consecutive integers, which is the best case for a Roaring bitmap.

Change what COUNT(DISTINCT) does

The count_distinct_implementation setting selects the function that COUNT(DISTINCT ...) uses. The default is uniqExact. You can switch it to an approximate function without rewriting queries: