> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Which function should I use to count distinct values in ClickHouse?

> Compares uniq, uniqExact, uniqCombined, uniqCombined64, uniqHLL12, uniqTheta, uniqUpTo and groupBitmap, and explains which one to use for counting distinct values.

Use [`uniq`](https://clickhouse.com/docs/reference/functions/aggregate-functions/uniq) when an approximate answer is acceptable, and [`uniqExact`](https://clickhouse.com/docs/reference/functions/aggregate-functions/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

| Function | Result | How it works | Use it when |
| - | - | - | - |
| [`uniqExact`](https://clickhouse.com/docs/reference/functions/aggregate-functions/uniqExact) | Exact | A hash table of all distinct values. The state grows with the number of distinct values. | You need the exact number. |
| [`uniq`](https://clickhouse.com/docs/reference/functions/aggregate-functions/uniq) | Approximate | Adaptive sampling: keeps a sample of up to 65536 hash values. Very efficient on the CPU. | The general case. The reference recommends it in almost all scenarios. |
| [`uniqCombined`](https://clickhouse.com/docs/reference/functions/aggregate-functions/uniqCombined) | Approximate | An array for small sets, then a hash table, then HyperLogLog with a fixed size. The base-2 logarithm of the number of HyperLogLog cells is an optional parameter (12 to 20, default 17). | You keep or transfer many states. Compared to `uniq`, it uses several times less memory and is several times more accurate, but is usually slightly slower. |
| [`uniqCombined64`](https://clickhouse.com/docs/reference/functions/aggregate-functions/uniqCombined64) | Approximate | The same as `uniqCombined`, with a 64-bit hash for all data types. `uniqCombined` uses a 32-bit hash for types other than `String`. | The number of distinct values can exceed `UINT_MAX` (about 4.3 billion). |
| [`uniqHLL12`](https://clickhouse.com/docs/reference/functions/aggregate-functions/uniqHLL12) | Approximate | HyperLogLog with 2^12 cells. | Not recommended. Use `uniq` or `uniqCombined` instead. |
| [`uniqTheta`](https://clickhouse.com/docs/reference/functions/aggregate-functions/uniqthetasketch) | Approximate | A Theta sketch: keeps the smallest hash values it has seen and estimates the count from the share of the hash space they cover. The documented relative error is 3.125% with 95% confidence. | You need set operations on the states: [`uniqThetaUnion`, `uniqThetaIntersect` and `uniqThetaNot`](https://clickhouse.com/docs/reference/functions/regular-functions/uniqtheta-functions). |
| [`uniqUpTo(N)`](https://clickhouse.com/docs/reference/functions/aggregate-functions/parametric-functions#uniquptonx) | Exact up to `N` | An array of up to `N` values (`N` is at most 100). Returns `N + 1` when there are more than `N` distinct values. | You only need to know whether the count reaches a small threshold. |
| [`groupBitmap`](https://clickhouse.com/docs/reference/functions/aggregate-functions/groupBitmap) | Exact | A Roaring bitmap. Works on integer values only. | The values are dense integer identifiers, or you need set operations with the [bitmap functions](https://clickhouse.com/docs/reference/functions/regular-functions/bitmap-functions.md). |

## Compare the results

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

```sql theme={null}
SELECT
    count(DISTINCT user_id) AS count_distinct,
    uniqExact(user_id) AS uniq_exact,
    uniq(user_id) AS uniq,
    uniqCombined(user_id) AS uniq_combined,
    uniqCombined64(user_id) AS uniq_combined64,
    uniqHLL12(user_id) AS uniq_hll12,
    uniqTheta(user_id) AS uniq_theta,
    uniqUpTo(10)(user_id) AS uniq_up_to_10,
    groupBitmap(user_id) AS group_bitmap
FROM
(
    SELECT number % 300000 AS user_id
    FROM numbers(1000000)
)
FORMAT Vertical;
```

```text theme={null}
Row 1:
──────
count_distinct:  300000
uniq_exact:      300000
uniq:            301750
uniq_combined:   300800
uniq_combined64: 300800
uniq_hll12:      298201
uniq_theta:      298099
uniq_up_to_10:   11
group_bitmap:    300000
```

## Why the size of the state matters

Each function keeps a state for every group of a `GROUP BY`. Consider a query like this:

```sql theme={null}
SELECT url, uniq(user_id)
FROM page_views
GROUP BY url;
```

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`](https://clickhouse.com/docs/reference/data-types/aggregatefunction) type (for example, in an [`AggregatingMergeTree`](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/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:

```sql theme={null}
SELECT
    n,
    length(CAST(uniqExactState(number) AS String)) AS uniq_exact,
    length(CAST(uniqState(number) AS String)) AS uniq,
    length(CAST(uniqCombinedState(number) AS String)) AS uniq_combined,
    length(CAST(uniqHLL12State(number) AS String)) AS uniq_hll12,
    length(CAST(uniqThetaState(number) AS String)) AS uniq_theta,
    length(CAST(uniqUpToState(10)(number) AS String)) AS uniq_up_to_10,
    length(CAST(groupBitmapState(number) AS String)) AS group_bitmap
FROM
(
    SELECT
        arrayJoin([2, 100, 10000, 1000000]) AS n,
        arrayJoin(range(n)) AS number
)
GROUP BY n
ORDER BY n;
```

```text theme={null}
   ┌───────n─┬─uniq_exact─┬───uniq─┬─uniq_combined─┬─uniq_hll12─┬─uniq_theta─┬─uniq_up_to_10─┬─group_bitmap─┐
1. │       2 │          9 │     11 │            10 │         10 │         33 │             9 │           10 │
2. │     100 │        401 │    403 │           402 │       2651 │        818 │             1 │           17 │
3. │   10000 │      40002 │  40004 │         81993 │       2651 │      42547 │             1 │           17 │
4. │ 1000000 │    4000003 │ 250503 │         81993 │       2651 │      52259 │             1 │          233 │
   └─────────┴────────────┴────────┴───────────────┴────────────┴────────────┴───────────────┴──────────────┘
```

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`](https://clickhouse.com/docs/reference/settings/session-settings/count-distinct#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:

```sql theme={null}
SELECT count(DISTINCT number % 300000) AS count_distinct
FROM numbers(1000000)
SETTINGS count_distinct_implementation = 'uniqCombined';
```

```text theme={null}
   ┌─count_distinct─┐
1. │         300800 │
   └────────────────┘
```
