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 aGROUP BY. Consider a query like this:
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:
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
Thecount_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: