HLL functions in the Apache DataSketches DuckDB extension
Sample data for the examples
Each browser example starts with these sample tables; sample files are shared across examples on this page. Run this setup first when trying the examples in your own DuckDB session.
SET VARIABLE example_today = (SELECT CURRENT_DATE);
-- Fixtures for the datasketches extension cookbook / technical-details /
-- functions.json examples. Provides the source tables that the snippets
-- reference (events, requests, page_views, measurements, …) so they can
-- actually execute under the validator instead of skipping with
-- "table fixture missing".
--
-- The validator's parse phase EXPLAINs each statement in a snippet
-- individually, so a snippet of the shape `CREATE TABLE foo …; SELECT
-- … FROM foo;` will fail to parse the SELECT (foo doesn't exist yet
-- during EXPLAIN). For the affected tables (daily_uniques, readings)
-- we pre-create them with the same column names + types the snippets
-- expect, so EXPLAIN succeeds. The snippets themselves use CREATE OR
-- REPLACE, so their own CREATE then rebuilds the table on execute.
----------------------------------------------------------------------
-- events: the catch-all source table referenced by HLL/CPC/Theta
-- examples. Carries enough columns to satisfy every reference:
-- user_id → distinct-count examples
-- ts → date_trunc('day', ts) for per-day rollups
-- country_code → frequent-items examples
-- cohort → datasketch_theta GROUP BY cohort example
----------------------------------------------------------------------
CREATE OR REPLACE TABLE events AS
SELECT
(i % 30) AS user_id,
(getvariable('example_today')::DATE + INTERVAL '-14 days')::TIMESTAMP
+ INTERVAL (i) HOUR AS ts,
(['US','GB','DE','FR','NO','SE','JP','CA','BR','AU'])[1 + (i % 10)]
AS country_code,
(['signup','active','dormant'])[1 + (i % 3)]
AS cohort
FROM range(0, 200) t(i);
----------------------------------------------------------------------
-- events_jan / events_feb: the Theta set-algebra (funnel/retention/
-- churn) example partitions users across two months. Overlapping but
-- not identical user-id ranges make the intersect / a-not-b results
-- non-trivial.
----------------------------------------------------------------------
CREATE OR REPLACE TABLE events_jan AS
SELECT (i % 50) AS user_id
FROM range(0, 200) t(i);
CREATE OR REPLACE TABLE events_feb AS
SELECT (20 + (i % 50)) AS user_id -- overlaps users 20..49 with jan
FROM range(0, 200) t(i);
----------------------------------------------------------------------
-- requests: latency_ms column for KLL / TDigest quantile examples.
-- Static deterministic values (no randomness) so sketch outputs are
-- reproducible across runs.
----------------------------------------------------------------------
CREATE OR REPLACE TABLE requests AS
SELECT (i * 7 % 1000)::INTEGER AS latency_ms
FROM range(0, 500) t(i);
----------------------------------------------------------------------
-- page_views: country_code column for the Frequent Items example.
----------------------------------------------------------------------
CREATE OR REPLACE TABLE page_views AS
SELECT
(['US','US','US','US','GB','GB','DE','FR','NO','SE','JP','CA','BR','AU','IT'])[1 + (i % 15)]
AS country_code
FROM range(0, 300) t(i);
----------------------------------------------------------------------
-- measurements: `value` column for the REQ skew-aware quantile
-- example. Mildly skewed via i*i to exercise the rank-error scaling.
----------------------------------------------------------------------
CREATE OR REPLACE TABLE measurements AS
SELECT (i * i)::DOUBLE AS value
FROM range(0, 100) t(i);
----------------------------------------------------------------------
-- daily_uniques: per-day HLL/Theta rollup table referenced by the
-- "Per-day HLL sketches" cookbook recipe, the technical-details
-- "billion-row distinct count" example, the datasketch_hll_union
-- example, and the persist-to-Parquet snippet. Schema matches what
-- the cookbook + functions.json snippets expect: (day DATE, hll
-- sketch_hll). The technical-details snippet builds its own (day,
-- sketch) shape with CREATE OR REPLACE TABLE … AS SELECT.
----------------------------------------------------------------------
CREATE OR REPLACE TABLE daily_uniques AS
SELECT
date_trunc('day', ts) AS day,
datasketch_hll(12, user_id) AS hll
FROM events
GROUP BY 1;
----------------------------------------------------------------------
-- readings: temp DOUBLE column for the TDigest cookbook examples.
-- Pre-seeded so the SELECT inside the same snippet binds at EXPLAIN
-- time. The snippet then re-creates it (CREATE OR REPLACE) with the
-- same shape on execute.
----------------------------------------------------------------------
CREATE OR REPLACE TABLE readings AS
SELECT i::DOUBLE AS temp
FROM range(1, 11) t(i);
----------------------------------------------------------------------
-- orders: per-order rows for the Tuple / array-of-doubles examples
-- (distinct customers carrying a per-customer revenue or metric vector).
----------------------------------------------------------------------
CREATE OR REPLACE TABLE orders AS
SELECT
(i % 40) AS customer_id,
(['north','south'])[1 + (i % 2)] AS region,
((i * 13) % 97 + 1)::DOUBLE AS amount,
(1 + i % 3)::DOUBLE AS items
FROM range(0, 400) t(i);
Function category
HLL
12 functionsHyperLogLog distinct-counting sketch — the industry standard. Fast serialize/deserialize and broad cross-system compatibility. Choose this when speed and interop matter more than storage.
Signature
2 overloaded forms · click to inspectArguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
k
|
Type
INTEGER
|
Mode Positional | Description |
Argument
data
|
Type
TINYINT | INTEGER | UTINYINT | …
15 concrete typesBIGINTBLOBDOUBLEFLOATHUGEINTINTEGERSMALLINTTINYINTUBIGINTUHUGEINTUINTEGERUSMALLINTUTINYINTUUIDVARCHAR
|
Mode Positional | Description |
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
k
|
Type
INTEGER
|
Mode Positional | Description |
Argument
data
|
Type
DOUBLE | UTINYINT | USMALLINT | …
15 concrete typesBIGINTBLOBDOUBLEFLOATHUGEINTINTEGERSMALLINTTINYINTUBIGINTUHUGEINTUINTEGERUSMALLINTUTINYINTUUIDVARCHAR
|
Mode Positional | Description |
Argument
target_type
|
Type
VARCHAR
|
Mode Positional | Description |
Description
Aggregate input values into a HyperLogLog sketch for distinct counting. Returns a sketch_hll BLOB you can persist, ship between processes, or merge later. The first argument is lg_k — base-2 log of the number of buckets — which controls the size/accuracy trade-off. lg_k = 12 (4096 buckets, ~4 KB sketch, ~1.6% standard error) is a common default; raise it for tighter bounds, lower it for smaller sketches. An optional third argument picks the register encoding: 'HLL_4' (the default, smallest), 'HLL_6' or 'HLL_8' (largest, fastest to update); it must be a constant, and parallel combines keep the chosen encoding. lg_k must be between 4 and 21. Input can be any integer, float, string, blob, UUID, HUGEINT, or UHUGEINT column; merge only sketches built from the same type, since values are hashed according to their column type. Returns NULL over no rows.
SELECT datasketch_hll_estimate(datasketch_hll(12, user_id)) AS distinct_users
FROM events;
CREATE OR REPLACE TABLE daily_uniques (day DATE, hll sketch_hll);
INSERT INTO daily_uniques
SELECT date_trunc('day', ts) AS day,
datasketch_hll(12, user_id) AS hll
FROM events
GROUP BY 1;
SELECT datasketch_hll_target_type(datasketch_hll(12, user_id, 'HLL_8')) AS encoding,
datasketch_hll_estimate(datasketch_hll(12, user_id, 'HLL_8')) AS distinct_users
FROM events;
Related functions
- datasketch_hll_estimate() — Read the estimated distinct count from an HLL sketch
- datasketch_hll_union() — Merge multiple HLL sketches into one
- datasketch_hll_lower_bound() — Lower bound of the HLL distinct-count estimate
- datasketch_hll_upper_bound() — Upper bound of the HLL distinct-count estimate
- datasketch_hll_describe() — Return a string representation of the sketch
- datasketch_hll_target_type() — Return the sketch's register encoding: 'HLL_4', 'HLL_6' or 'HLL_8'
- datasketch_hll_merge() — Scalar union of two HLL sketches — the row-wise counterpart of the `datasketch_hll_union` aggregate (the scalar is named `_merge` because a scalar and an aggregate cannot share a name)
Signature
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
sketch
|
Type
sketch_hll
|
Mode Positional | Description |
Description
Return the composite estimate of the number of distinct items, computed from the registers alone (the raw HLL estimate blended with linear counting). datasketch_hll_estimate prefers the HIP estimator, which is only available for sketches that were not built by a union
SELECT datasketch_hll_composite_estimate(sketch) FROM (SELECT datasketch_hll(12, i) AS sketch FROM range(100) t(i)) s;
Output
| datasketch_hll_composite_estimate(sketch) |
|---|
| 100.00002458692298 |
Related functions
Signature
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
sketch
|
Type
sketch_hll
|
Mode Positional | Description |
Argument
summary
|
Type
BOOLEAN
|
Mode Positional | Description |
Argument
detail
|
Type
BOOLEAN
|
Mode Positional | Description |
Description
Return a string representation of the sketch
SELECT datasketch_hll_describe(sketch, true, false) FROM (SELECT datasketch_hll(12, i) AS sketch FROM range(100) t(i)) s;
Output
| datasketch_hll_describe(sketch, true, false) |
|---|
### HLL sketch summary: Log Config K : 12 Hll Target : HLL_4 Current Mode : SET LB : 100 Estimate : 100 UB : 100.005 OutOfOrder flag: false Coupon count : 100 ### End HLL sketch summary |
Signature
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
sketch
|
Type
sketch_hll
|
Mode Positional | Description |
Description
Read the estimated distinct count from an HLL sketch. Returns a DOUBLE — the cardinality estimate.
SELECT datasketch_hll_estimate(sketch) FROM (SELECT datasketch_hll(12, i) AS sketch FROM range(100) t(i)) s;
Output
| datasketch_hll_estimate(sketch) |
|---|
| 100.00002458692298 |
Related functions
- datasketch_hll() — Aggregate input values into a HyperLogLog sketch for distinct counting
- datasketch_hll_union() — Merge multiple HLL sketches into one
- datasketch_hll_lower_bound() — Lower bound of the HLL distinct-count estimate
- datasketch_hll_upper_bound() — Upper bound of the HLL distinct-count estimate
- datasketch_hll_composite_estimate() — Return the composite estimate of the number of distinct items, computed from the registers alone (the raw HLL estimate blended with linear counting)
Signature
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
sketch
|
Type
sketch_hll
|
Mode Positional | Description |
Description
Return whether the sketch is in compact form
SELECT datasketch_hll_is_compact(sketch) FROM (SELECT datasketch_hll(12, i) AS sketch FROM range(100) t(i)) s;
Output
| datasketch_hll_is_compact(sketch) |
|---|
| false |
Signature
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
sketch
|
Type
sketch_hll
|
Mode Positional | Description |
Description
Return a boolean indicating if the sketch is empty
SELECT datasketch_hll_is_empty(sketch) FROM (SELECT datasketch_hll(12, i) AS sketch FROM range(100) t(i)) s;
Output
| datasketch_hll_is_empty(sketch) |
|---|
| false |
Signature
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
sketch
|
Type
sketch_hll
|
Mode Positional | Description |
Description
Return the value of log base 2 K for this sketch
SELECT datasketch_hll_lg_config_k(sketch) FROM (SELECT datasketch_hll(12, i) AS sketch FROM range(100) t(i)) s;
Output
| datasketch_hll_lg_config_k(sketch) |
|---|
| 12 |
Signature
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
sketch
|
Type
sketch_hll
|
Mode Positional | Description |
Argument
num_std_devs
|
Type
INTEGER
|
Mode Positional | Description |
Description
Lower bound of the HLL distinct-count estimate. num_std_devs (1, 2, or 3 — roughly 68%, 95%, and 99.7% confidence) sets the width of the interval; any other value is an error.
SELECT datasketch_hll_lower_bound(sketch, 2) FROM (SELECT datasketch_hll(12, i) AS sketch FROM range(100) t(i)) s;
Output
| datasketch_hll_lower_bound(sketch, 2) |
|---|
| 100.0 |
Signature
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
sketch_a
|
Type
sketch_hll
|
Mode Positional | Description |
Argument
sketch_b
|
Type
sketch_hll
|
Mode Positional | Description |
Description
Scalar union of two HLL sketches — the row-wise counterpart of the datasketch_hll_union aggregate (the scalar is named _merge because a scalar and an aggregate cannot share a name). The result keeps the first sketch's target type; the union runs at the larger lg_config_k of the two, and if either input is in dense (HLL) mode the result is reduced to the smaller one.
WITH a AS (SELECT datasketch_hll(12, user_id) AS s FROM events_jan),
b AS (SELECT datasketch_hll(12, user_id) AS s FROM events_feb)
SELECT datasketch_hll_estimate(datasketch_hll_merge(a.s, b.s)) AS jan_or_feb
FROM a, b;
Signature
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
sketch
|
Type
sketch_hll
|
Mode Positional | Description |
Description
Return the sketch's register encoding: 'HLL_4', 'HLL_6' or 'HLL_8'
SELECT datasketch_hll_target_type(sketch) FROM (SELECT datasketch_hll(12, i) AS sketch FROM range(100) t(i)) s;
Output
| datasketch_hll_target_type(sketch) |
|---|
| HLL_4 |
Signature
2 overloaded forms · click to inspectArguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
k
|
Type
INTEGER
|
Mode Positional | Description |
Argument
sketch
|
Type
sketch_hll
|
Mode Positional | Description |
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
k
|
Type
INTEGER
|
Mode Positional | Description |
Argument
sketch
|
Type
sketch_hll
|
Mode Positional | Description |
Argument
target_type
|
Type
VARCHAR
|
Mode Positional | Description |
Description
Merge multiple HLL sketches into one. Aggregate over a column of sketch_hll BLOBs to roll per-partition or per-day sketches up to whatever window you need — without rescanning the underlying rows. The leading lg_k argument is the precision of the output sketch. An optional third argument ('HLL_4', 'HLL_6' or 'HLL_8') sets the encoding of the result. To union just two sketches in a row-wise expression, use the scalar datasketch_hll_merge. Merge only sketches built from the same input type.
SELECT datasketch_hll_estimate(datasketch_hll_union(12, hll)) AS uniques_last_7d
FROM daily_uniques
WHERE day >= CURRENT_DATE + INTERVAL '-7 days';
Related functions
- datasketch_hll() — Aggregate input values into a HyperLogLog sketch for distinct counting
- datasketch_hll_estimate() — Read the estimated distinct count from an HLL sketch
- datasketch_hll_merge() — Scalar union of two HLL sketches — the row-wise counterpart of the `datasketch_hll_union` aggregate (the scalar is named `_merge` because a scalar and an aggregate cannot share a name)
Signature
Arguments (Positional)
| Argument | Type | Mode | Description |
|---|---|---|---|
Argument
sketch
|
Type
sketch_hll
|
Mode Positional | Description |
Argument
num_std_devs
|
Type
INTEGER
|
Mode Positional | Description |
Description
Upper bound of the HLL distinct-count estimate. num_std_devs (1, 2, or 3 — roughly 68%, 95%, and 99.7% confidence) sets the width of the interval; any other value is an error.
SELECT datasketch_hll_upper_bound(sketch, 2) FROM (SELECT datasketch_hll(12, i) AS sketch FROM range(100) t(i)) s;
Output
| datasketch_hll_upper_bound(sketch, 2) |
|---|
| 100.01001093811284 |