DuckDB Extension
Apache DataSketches
Build and merge Apache DataSketches in DuckDB. Estimate distinct counts, quantiles, and frequent items from compact summaries stored as BLOBs.
On this page
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);
Keep a small summary instead of every observation
A sketch summarizes a large collection of values in a compact data structure. Apache DataSketches provides algorithms for questions such as how many distinct values appeared, which items are frequent, or where a percentile falls.
This extension lets you build sketches from DuckDB columns, store them, and merge them later. For example, daily sketches can produce a longer-period estimate without rereading all the original rows. Choose the sketch family and size according to the question and the approximation you can accept.
Example
Estimate distinct visitors
Five sample events contain three distinct user IDs. Build an HLL sketch, then read its estimate.
Tested with DuckDB 1.5.6. Browser examples use Haybarn-Wasm 2.0.0-rc12.
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://duckdb-extensions.query.farm';
INSTALL datasketches FROM query_farm;
LOAD datasketches FROM query_farm;
WITH events(user_id) AS (
VALUES (101), (102), (101), (103), (102)
), summary AS (
SELECT datasketch_hll(12, user_id) AS sketch FROM events
)
SELECT round(datasketch_hll_estimate(sketch), 2) AS estimated_users
FROM summary;
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://haybarn-extensions.query.farm';
INSTALL datasketches FROM query_farm;
LOAD datasketches FROM query_farm;
WITH events(user_id) AS (
VALUES (101), (102), (101), (103), (102)
), summary AS (
SELECT datasketch_hll(12, user_id) AS sketch FROM events
)
SELECT round(datasketch_hll_estimate(sketch), 2) AS estimated_users
FROM summary;
INSTALL datasketches FROM community;
LOAD datasketches;
WITH events(user_id) AS (
VALUES (101), (102), (101), (103), (102)
), summary AS (
SELECT datasketch_hll(12, user_id) AS sketch FROM events
)
SELECT round(datasketch_hll_estimate(sketch), 2) AS estimated_users
FROM summary;
Expected result
| estimated_users |
|---|
| 3 |
This small example demonstrates the API. Sketches are useful when you need compact, mergeable summaries; their estimates are approximate.
Common tasks
Deep Dive
Technical Details
DuckDB β Apache DataSketches
Mergeable, persistable streaming sketches β distinct counts, quantiles, and heavy hitters β from the Apache DataSketches library.
A billion-row distinct count, persisted
A naive COUNT(DISTINCT user_id) over a billion-row event table is a sort plus a hash table β minutes of work, gigabytes of memory, a fresh scan every time someone asks again. With a Theta sketch, itβs a fixed-memory aggregate you build once per partition and roll up on demand:
-- One pass, per-day sketch state, persisted as a typed BLOB columnCREATE OR REPLACE TABLE daily_uniques ASSELECT date_trunc('day', ts) AS day, datasketch_theta(12, user_id) AS sketch -- ~64 KB per dayFROM eventsGROUP BY 1;
-- Rolling 7-day uniques: union the per-day sketches, no rescanSELECT datasketch_theta_estimate( datasketch_theta(sketch) -- merge aggregate over sketches ) AS uniques_last_7dFROM daily_uniquesWHERE day >= CURRENT_DATE + INTERVAL '-7 days';
-- Retention: users active in BOTH last week AND this weekWITH last_week AS (SELECT datasketch_theta(sketch) AS s FROM daily_uniques WHERE day BETWEEN CURRENT_DATE + INTERVAL '-14 days' AND CURRENT_DATE + INTERVAL '-7 days'), this_week AS (SELECT datasketch_theta(sketch) AS s FROM daily_uniques WHERE day >= CURRENT_DATE + INTERVAL '-7 days')SELECT datasketch_theta_estimate( datasketch_theta_intersect(last_week.s, this_week.s) ) AS retainedFROM last_week, this_week;The first query touches the source rows once. The next two β and any other window, set difference, or intersection you care to ask β operate on the sketch state alone.
Sketches are not a faster way to get exact answers. They give bounded-memory, mergeable, approximately correct aggregates with a small, predictable error. The default HLL sketch (lg_k = 12) is roughly Β±1.6% on distinct counts; the default KLL (K = 200) puts quantile error at roughly Β±1.5% rank. Pick the size knob to match your accuracy budget β and donβt reach for sketches when policy demands exact (billing, audits, reconciliation).
Architecture
This extension is a thin DuckDB wrapper around the Apache DataSketches C++ library. Every sketch family registers:
- An aggregate (
datasketch_kll,datasketch_hll,datasketch_theta, β¦) that builds the sketch in one pass over input values. - A typed BLOB column type (
sketch_kll_double,sketch_hll,sketch_theta, β¦) β a strict superset ofBLOBcarrying the serialized sketch. - Reader scalars (
datasketch_*_quantile,datasketch_*_estimate,datasketch_*_cdf, β¦) that decode the BLOB and return values without rebuilding from rows. - Mergers β aggregates over a sketch column that produce a rolled-up sketch (
datasketch_hll_union,datasketch_cpc_union, or the sketch aggregate itself given a sketch, e.g.datasketch_theta(sketch),datasketch_kll(200, sketch)), plus scalar unions of sketches in the same row (datasketch_hll_merge,datasketch_cpc_merge,datasketch_theta_union(a, b, β¦)).
Every sketch aggregate returns NULL when it sees no input rows (or only NULLs), like any SQL aggregate, so wrap an estimate in coalesce(..., 0) where an empty group should read as zero.
The serialization format is the same one the Java reference implementation writes, which is the format Druid, Pinot, BigQuery, and Spark integrations consume. A sketch built in DuckDB and written to Parquet can be merged inside Druid or vice versa β no re-aggregation across systems.
Choosing a sketch
The right sketch depends on what youβre estimating and which constraint binds first β read latency, sketch size, or set algebra.
Distinct counts (cardinality)
| Family | When to pick | Notes |
|---|---|---|
| HLL | Default β fastest reads, broad cross-system interop | lg_k 4β21; 12 is a good default (~4 KB sketch) |
| CPC | Storage-bound β many sketches at rest | lg_k 4β26; ~40% smaller than HLL at the same accuracy |
| Theta | You need union, intersection, or A-not-B (funnel, retention, churn) | lg_k 4β26; only family with full set algebra |
Distinct keys with per-key metrics
| Family | When to pick | Notes |
|---|---|---|
| Tuple | Distinct keys and one metric per key (customers + revenue) | mode := sum / min / max / one; Theta set algebra |
| Array of Doubles | Distinct keys with several metrics per key | 1β255 DOUBLE values per key, summed element-wise |
Quantiles
| Family | When to pick | Notes |
|---|---|---|
| KLL | Default β best accuracy/size balance | K 8β65535; 200 is a sensible production starting point; numeric or VARCHAR items |
| TDigest | p99 / p999 SLO reporting | K 10β65535; FLOAT/DOUBLE only; tail-accurate |
| REQ | Skewed distributions | K 4β1024; error scales with rank; high-rank (default) or low-rank accuracy |
| Quantiles | Compatibility with classic pipelines | K a power of 2 from 2 to 32768; use KLL for new work; numeric or VARCHAR items |
A size argument outside its familyβs range is rejected when the query binds, rather than failing mid-query or being silently truncated.
Frequency
A single family β Frequent Items β for top-K heavy hitters with confidence-bounded frequencies. Use 'NO_FALSE_POSITIVES' to get items that are definitely heavy, 'NO_FALSE_NEGATIVES' to get every candidate that might be (the error type is case-insensitive; anything else is an error). datasketch_frequent_items_weighted adds a per-row BIGINT/UBIGINT weight for top-K by revenue, bytes, or any other metric.
Compared to alternatives
- DuckDBβs built-in
approx_count_distinctandapprox_quantileβ both ship in DuckDB and use HLL / TDigest internally, but expose only the final estimate. Reach for this extension when you need the sketch as state β to persist it as a column, merge later, tune sketch parameters (lg_k,K,map_size), or interoperate with other Apache DataSketches consumers. - Exact aggregates (
COUNT(DISTINCT),quantile_cont,mode) β the right answer when policy demands exact and your data fits. DuckDBβs vectorized exact aggregates are fast at most analytical scales; measure before reaching for an approximate sketch. - Reservoir / streaming aggregates rolled by hand β sketches give you the same bounded-memory streaming property plus mathematically grounded error bounds plus mergeability across processes. For anything that needs to survive a process restart or roll up across shards, the sketch is the better primitive.
- Druid / Pinot / BigQuery sketch columns β those systems use the same serialization format. If youβre already producing sketches there, this extension lets DuckDB read and merge them; if youβre building them in DuckDB, downstream OLAP systems can consume the BLOBs directly.
Persistence and portability
Every sketch round-trips through a typed BLOB column (sketch_kll_double, sketch_hll, sketch_theta, etc.) thatβs a strict superset of BLOB. Sketches written into a Parquet file can be read back into any DuckDB instance with this extension loaded, or into any other DataSketches-aware system, and merged without a re-scan. Aggregate functions accept either raw input values or an existing sketch column, so incremental rollup is just another SELECT.
Merging HLL and CPC sketches across types
HLL and CPC accept integers, floats, strings, blobs, UUID, HUGEINT and UHUGEINT, and hash each value according to its column type. Merge only sketches built from the same type β across types, equal values can hash differently:
- Integers up to 64 bits hash by value (
5::UTINYINTand5::BIGINTmatch), but an unsigned value is first read as the signed value of the same width, so200::UTINYINThashes like-56. - A
HUGEINTorUHUGEINTthat fits in aBIGINThashes like thatBIGINTβ so sketches ofsum()results (which DuckDB returns asHUGEINT) merge with sketches of the sameBIGINTvalues. Wider values hash all 16 bytes. - Integers and floating-point values never match:
5::BIGINTand5::DOUBLEdiffer. - A
UUIDhashes the same 16 bytes asuuid::BLOB.
If values arrive in different types, cast them to one type before sketching.
Tuple sketches: distinct keys that carry values
A Tuple sketch is a Theta sketch in which every retained key also carries a summary. datasketch_tuple(key, value) keeps one DOUBLE per key, combined by mode := β 'sum' (default), 'min', 'max' or 'one' β so one pass answers both βhow many distinct customers?β and βhow much did they spend?β:
SELECT datasketch_tuple_estimate(s) AS customers, datasketch_tuple_sum(s) AS revenue, -- estimated total over all keys datasketch_tuple_mean(s) AS revenue_per_customerFROM (SELECT datasketch_tuple(customer_id, amount) AS s FROM orders);datasketch_aod(key, [m1, m2, β¦]) is the array-of-doubles variant: each key carries 1β255 DOUBLE values summed element-wise, read back with datasketch_aod_column_sums / datasketch_aod_column_means. Both families support the Theta algebra (_union, _intersect, _intersect_agg, _a_not_b), Jaccard similarity on the key sets, and conversion to a plain Theta sketch with _to_theta. The Tuple sketchβs mode is not stored in the sketch (as in the other DataSketches libraries), so pass the same mode := to merges, unions and intersections. Sketches with different seeds β or array-of-doubles sketches with different numbers of values β cannot be combined.
Theta options: seeds, sampling, and storage
datasketch_theta, datasketch_tuple and datasketch_aod take keyword options seed := (the hash seed) and p := (an up-front sampling probability in (0, 1]). Compact sketches store only a 16-bit hash of the seed (datasketch_theta_seed_hash), and every function reads and combines seeded sketches without being told the seed again; combining sketches whose seed hashes differ is an error. Unions keep the largest lg_k of their inputs (at least 12) unless you pass one. Theta results are written in the compressed compact format (serial version 4) when it applies; versions 1β4 are all readable, and DataSketches C++ 4.0+, Java and Python read version 4. To hash raw BLOB bytes use datasketch_theta_blob β datasketch_theta(BLOB) merges serialized sketches.
Behavior changes in recent releases
The October 2026 releases (Apache DataSketches C++ 5.3.0) change a few behaviors. Unless marked DuckDB 2.0 build, the change also ships in the current DuckDB 1.5 build.
- CDF and PMF always return
LIST(DOUBLE)(DuckDB 2.0 build).datasketch_{kll,quantiles,req}_cdfand_pmfused to return a list of the sketchβs item type, which truncated CDF ranks for integer sketches and could corrupt PMF results. Update code that expects, say,INTEGER[]. - Frequent Items keys for FLOAT/DOUBLE are exact. Items are now keyed by their shortest round-trip text (like
CAST(x AS VARCHAR)) instead of six fixed decimals, so0.1234567and0.1234568stay distinct. Sketches of FLOAT/DOUBLE items built by earlier versions hold the old spellings: lookups against them usually return 0 and merges keep both spellings, so rebuild them from source data. VARCHAR and integer sketches are unaffected.lg_max_kmust now be between 3 and 30 (out-of-range values used to be silently truncated). - Theta unions keep their size.
datasketch_theta_unionand thedatasketch_theta(sketch)merge used to run atlg_k12 regardless of their inputs; they now keep the inputsβlg_k. - Constant arguments are honored. Queries that combined the same aggregate with different constant sizes (e.g.
datasketch_kll(12, v)anddatasketch_kll(16, v)in oneUNION ALL) could previously return the first sketch twice. - Empty input gives
NULL. Every sketch aggregate now returnsNULLover no rows. Theta, Tuple, array-of-doubles and Frequent Items used to return an empty sketch, so an estimate over an empty group is nowNULLrather than 0 β wrap it incoalesce(..., 0)for the old result. Merging only empty sketches still returns an empty sketch. - Size arguments are validated.
K/lg_kvalues outside each familyβs range (see the tables above) are bind errors; previously some failed mid-query and others were silently changed (a REQKof 256 became 4, a T-DigestKof 70000 became 4464). - HLL and CPC bounds take
num_std_devs.datasketch_{hll,cpc}_{lower,upper}_boundnow takenum_std_devs INTEGER(1, 2 or 3), like the Theta bounds, instead ofstd_dev UTINYINT; other values are an error. - HLL and CPC accept
UUID,HUGEINTandUHUGEINT.HUGEINT/UHUGEINTused to go throughDOUBLE, so values beyond 2^53 collapsed; see Merging HLL and CPC sketches across types. HUGEINT sketches built by earlier versions do not merge with new ones. - Stricter errors. A
NULLsplit point in a CDF or PMF is an error (it used to read whatever value sat in the vector); library failures surface asInvalid Input Error: <function>: β¦; corrupt Theta and Frequent Items sketches reportFailed to deserialize β¦ sketch; aNULLlg_max_kis an error; and casts tosketch_hll,sketch_cpc,sketch_thetaandsketch_frequent_itemskeep the sketch type instead ofBLOB. - New in the DuckDB 2.0 build: Tuple and array-of-doubles sketches; batch
_quantiles/_ranksand_sorted_viewfor KLL, Quantiles and REQ; VARCHAR items for KLL and Quantiles; REQ accuracy mode and rank bounds; T-Digest exact min/max; HLL register encodings, composite estimate anddatasketch_hll_merge/datasketch_cpc_merge; Theta Jaccard similarity,datasketch_theta_intersect_agg, variadic union/intersect,seed :=/p :=options, unsigned-integer input,datasketch_theta_bloband compressed storage.datasketch_theta_get_seedis now documented as an alias ofdatasketch_theta_seed_hash(it always returned the seed hash).
Reference
Extension Contents
Quick reference to all available functions and settings organized by category.
| Name | Type | Description |
|---|---|---|
|
Array of Doubles
Array-of-doubles Tuple sketch β like the Tuple sketch, but every key carries a fixed-length array of DOUBLE values (1β255) summed element-wise, so one sketch tracks several metrics per distinct key. |
||
| datasketch_aod() | Object type: Aggregate function |
Aggregate (key, values DOUBLE[]) rows into an array-of-doubles Tuple sketch (sketch_aod): a Theta sketch of the distinct keys where each retained key carries a fixed-length array of DOUBLE values (1β255 values, the same length on every row, inferred from the data and stored in the sketch), summed element-wise per key.
|
| datasketch_aod_a_not_b() | Object type: Scalar function | Returns a new array-of-doubles sketch with the keys (and their summaries) of sketch A that are not in sketch B (set difference) |
| datasketch_aod_column_means() | Object type: Scalar function | Returns the mean of each value column over the retained keys (the mean per distinct key), or NULL if the sketch retains no entries |
| datasketch_aod_column_sums() | Object type: Scalar function | Returns the estimated total of each value column over all distinct keys: the column sums of the retained entries divided by theta (exact when the sketch is not in estimation mode) |
| datasketch_aod_describe() | Object type: Scalar function | Returns a human-readable description of the array-of-doubles sketch |
| datasketch_aod_dissimilarity_test() | Object type: Scalar function | Returns true if the Jaccard similarity of the key sets is at most the threshold, with high confidence (its upper bound is <= threshold) |
| datasketch_aod_estimate() | Object type: Scalar function | Returns the estimated number of distinct keys in the array-of-doubles sketch |
| datasketch_aod_exactly_equal() | Object type: Scalar function | Returns true if the two sketches retain exactly the same keys with the same theta (summaries are not compared) |
| datasketch_aod_get_theta() | Object type: Scalar function | Returns the theta value of the array-of-doubles sketch (the fraction of the key hash space it retains) |
| datasketch_aod_intersect() | Object type: Scalar function | Returns the intersection of two or more array-of-doubles sketches: the keys present in every sketch, with their values summed element-wise |
| datasketch_aod_intersect_agg() | Object type: Aggregate function | Intersects array-of-doubles sketches across rows: keeps the keys present in every sketch, summing their values element-wise. |
| datasketch_aod_is_empty() | Object type: Scalar function | Returns true if the array-of-doubles sketch is empty |
| datasketch_aod_is_estimation_mode() | Object type: Scalar function | Returns true if the array-of-doubles sketch is in estimation mode (it has sampled the keys) |
| datasketch_aod_jaccard() | Object type: Scalar function | Returns the Jaccard similarity of the key sets of two sketches as a struct of its estimate and approximate lower and upper bounds (about 2 standard deviations). |
| datasketch_aod_lower_bound() | Object type: Scalar function | Returns the lower bound of the estimated number of distinct keys at the given number of standard deviations (1, 2, or 3) |
| datasketch_aod_num_retained() | Object type: Scalar function | Returns the number of entries (keys with their summaries) retained in the array-of-doubles sketch |
| datasketch_aod_num_values() | Object type: Scalar function | Returns the number of values per key of the array-of-doubles sketch |
| datasketch_aod_seed_hash() | Object type: Scalar function | Returns the 16-bit hash of the seed the array-of-doubles sketch was built with; sketches can only be combined if their seed hashes match |
| datasketch_aod_similarity_test() | Object type: Scalar function | Returns true if the Jaccard similarity of the key sets is at least the threshold, with high confidence (its lower bound is >= threshold) |
| datasketch_aod_summaries() | Object type: Scalar function | Returns the retained entries of the array-of-doubles sketch as a list of {hash, values} structs (the key hash and its values) |
| datasketch_aod_to_theta() | Object type: Scalar function | Converts the array-of-doubles sketch to a Theta sketch of its keys (dropping the summaries), usable with the datasketch_theta functions |
| datasketch_aod_union() | Object type: Scalar function | Returns the union of two or more array-of-doubles sketches (values of a key summed element-wise), keeping as many entries as the largest input (at least lg_k 12) |
| datasketch_aod_upper_bound() | Object type: Scalar function | Returns the upper bound of the estimated number of distinct keys at the given number of standard deviations (1, 2, or 3) |
|
CPC
Compressed Probability Counting β distinct-counting at roughly 40% the size of HLL at the same accuracy, traded against slower serialization. Choose this when you store many sketches at rest. |
||
| datasketch_cpc() | Object type: Aggregate function | Aggregate input values into a Compressed Probability Counting sketch β a distinct-count sketch that's roughly 40% smaller than HLL at the same accuracy, traded against slower serialization. |
| datasketch_cpc_describe() | Object type: Scalar function | Return a string representation of the sketch |
| datasketch_cpc_estimate() | Object type: Scalar function | Read the estimated distinct count from a CPC sketch. |
| datasketch_cpc_is_empty() | Object type: Scalar function | Return a boolean indicating if the sketch is empty |
| datasketch_cpc_lower_bound() | Object type: Scalar function | Lower bound of the CPC distinct-count estimate. |
| datasketch_cpc_merge() | Object type: Scalar function |
Scalar union of two CPC sketches β the row-wise counterpart of the datasketch_cpc_union aggregate.
|
| datasketch_cpc_union() | Object type: Aggregate function |
Merge a column of sketch_cpc BLOBs into one rollup sketch β the standard per-partition / per-day rollup pattern.
|
| datasketch_cpc_upper_bound() | Object type: Scalar function | Upper bound of the CPC distinct-count estimate. |
|
Frequent Items
Heavy-hitter sketch that identifies the most-frequent items in a stream along with confidence-bounded frequency estimates. Use for top-N analysis on high-cardinality streams where exact |
||
| datasketch_frequent_items() | Object type: Aggregate function | Aggregate input values into a Frequent Items (heavy-hitter) sketch. |
| datasketch_frequent_items_epsilon() | Object type: Scalar function | Returns the epsilon value (relative error) of the sketch |
| datasketch_frequent_items_estimate() | Object type: Scalar function | Estimated frequency for a specific item. |
| datasketch_frequent_items_get_frequent() | Object type: Scalar function | Return the heavy-hitter candidates with per-item estimate, lower bound, and upper bound. |
| datasketch_frequent_items_is_empty() | Object type: Scalar function | Returns true if the sketch is empty |
| datasketch_frequent_items_lower_bound() | Object type: Scalar function | Returns the lower bound frequency estimate for a specific item |
| datasketch_frequent_items_num_active() | Object type: Scalar function | Returns the number of active items currently tracked by the sketch |
| datasketch_frequent_items_total_weight() | Object type: Scalar function | Returns the total weight (sum of all item counts) processed by the sketch |
| datasketch_frequent_items_upper_bound() | Object type: Scalar function | Returns the upper bound frequency estimate for a specific item |
| datasketch_frequent_items_weighted() | Object type: Aggregate function |
Like datasketch_frequent_items, but each row adds a weight (BIGINT or UBIGINT; negative weights are rejected) instead of a count of one β approximate top-K by a metric such as revenue or bytes.
|
|
HLL
HyperLogLog distinct-counting sketch β the industry standard. Fast serialize/deserialize and broad cross-system compatibility. Choose this when speed and interop matter more than storage. |
||
| datasketch_hll() | Object type: Aggregate function | Aggregate input values into a HyperLogLog sketch for distinct counting. |
| datasketch_hll_composite_estimate() | Object type: Scalar function | 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_describe() | Object type: Scalar function | Return a string representation of the sketch |
| datasketch_hll_estimate() | Object type: Scalar function | Read the estimated distinct count from an HLL sketch. |
| datasketch_hll_is_compact() | Object type: Scalar function | Return whether the sketch is in compact form |
| datasketch_hll_is_empty() | Object type: Scalar function | Return a boolean indicating if the sketch is empty |
| datasketch_hll_lg_config_k() | Object type: Scalar function | Return the value of log base 2 K for this sketch |
| datasketch_hll_lower_bound() | Object type: Scalar function | Lower bound of the HLL distinct-count estimate. |
| datasketch_hll_merge() | Object type: Scalar function |
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).
|
| datasketch_hll_target_type() | Object type: Scalar function | Return the sketch's register encoding: 'HLL_4', 'HLL_6' or 'HLL_8' |
| datasketch_hll_union() | Object type: Aggregate function | Merge multiple HLL sketches into one. |
| datasketch_hll_upper_bound() | Object type: Scalar function | Upper bound of the HLL distinct-count estimate. |
|
KLL
KLL quantile sketch β modern mergeable quantile estimator. Best balance of accuracy, speed, and size for general-purpose quantile work. Default choice unless you have a specific reason to pick TDigest or REQ. |
||
| datasketch_kll() | Object type: Aggregate function | Aggregate input values into a KLL quantile sketch. |
| datasketch_kll_cdf() | Object type: Scalar function | CDF over a list of split points β one call returns the cumulative rank at each. |
| datasketch_kll_describe() | Object type: Scalar function | Return a description of this sketch |
| datasketch_kll_is_empty() | Object type: Scalar function | Return a boolean indicating if the sketch is empty |
| datasketch_kll_is_estimation_mode() | Object type: Scalar function | Return a boolean indicating if the sketch is in estimation mode |
| datasketch_kll_k() | Object type: Scalar function | Return the value of K for this sketch |
| datasketch_kll_max_item() | Object type: Scalar function | Return the maximum item in the sketch |
| datasketch_kll_min_item() | Object type: Scalar function | Return the minimum item in the sketch |
| datasketch_kll_n() | Object type: Scalar function | Return the number of items contained in the sketch |
| datasketch_kll_normalized_rank_error() | Object type: Scalar function | Return the normalized rank error of the sketch |
| datasketch_kll_num_retained() | Object type: Scalar function | Return the number of retained items in the sketch |
| datasketch_kll_pmf() | Object type: Scalar function | PMF (probability mass) over a list of split points β fraction of the distribution falling in each bucket. |
| datasketch_kll_quantile() | Object type: Scalar function |
Approximate quantile at a given rank β given a sketch and r β [0, 1], returns the value at that rank in the sorted distribution.
|
| datasketch_kll_quantiles() | Object type: Scalar function | Return the quantiles (items) at a list of normalized ranks in [0, 1]. |
| datasketch_kll_rank() | Object type: Scalar function |
Inverse of datasketch_kll_quantile β given a value, return its approximate rank r β [0, 1] in the sorted distribution.
|
| datasketch_kll_ranks() | Object type: Scalar function | Return the normalized ranks of a list of items. |
| datasketch_kll_sorted_view() | Object type: Scalar function | Return the sketch's sorted view: one entry per retained item in ascending order (equal items can appear more than once), with the item's weight and the inclusive cumulative weight (the number of input items less than or equal to it; estimated once the sketch is in estimation mode). |
|
Quantiles
Classic mergeable quantile sketch from the original DataSketches paper. Solid general-purpose choice supporting all numeric types; KLL is now preferred for new projects. |
||
| datasketch_quantiles() | Object type: Aggregate function | Aggregate input values into the classic mergeable quantiles sketch from the original DataSketches paper. |
| datasketch_quantiles_cdf() | Object type: Scalar function | CDF over a list of split points β the cumulative rank at each split point, plus a final 1.0. |
| datasketch_quantiles_describe() | Object type: Scalar function | Return a description of this sketch |
| datasketch_quantiles_is_empty() | Object type: Scalar function | Return a boolean indicating if the sketch is empty |
| datasketch_quantiles_is_estimation_mode() | Object type: Scalar function | Return a boolean indicating if the sketch is in estimation mode |
| datasketch_quantiles_k() | Object type: Scalar function | Return the value of K for this sketch |
| datasketch_quantiles_max_item() | Object type: Scalar function | Return the maximum item in the sketch |
| datasketch_quantiles_min_item() | Object type: Scalar function | Return the minimum item in the sketch |
| datasketch_quantiles_n() | Object type: Scalar function | Return the number of items contained in the sketch |
| datasketch_quantiles_normalized_rank_error() | Object type: Scalar function | Return the normalized rank error of the sketch |
| datasketch_quantiles_num_retained() | Object type: Scalar function | Return the number of retained items in the sketch |
| datasketch_quantiles_pmf() | Object type: Scalar function | PMF (probability mass) over a list of split points β the fraction of the distribution falling in each bucket. |
| datasketch_quantiles_quantile() | Object type: Scalar function | Approximate quantile at a given rank from a classic Quantiles sketch. |
| datasketch_quantiles_quantiles() | Object type: Scalar function | Return the quantiles (items) at a list of normalized ranks in [0, 1]. |
| datasketch_quantiles_rank() | Object type: Scalar function | Approximate rank of a value within the classic Quantiles sketch. |
| datasketch_quantiles_ranks() | Object type: Scalar function | Return the normalized ranks of a list of items. |
| datasketch_quantiles_sorted_view() | Object type: Scalar function | Return the sketch's sorted view: one entry per retained item in ascending order (equal items can appear more than once), with the item's weight and the inclusive cumulative weight (the number of input items less than or equal to it; estimated once the sketch is in estimation mode). |
|
REQ
Relative-error quantile sketch. Error scales with rank rather than being fixed across the distribution β predictable accuracy on highly skewed data. |
||
| datasketch_req() | Object type: Aggregate function | Aggregate input values into a Relative Error Quantile sketch. |
| datasketch_req_cdf() | Object type: Scalar function | CDF over a list of split points β the cumulative rank at each split point, plus a final 1.0. |
| datasketch_req_describe() | Object type: Scalar function | Return a description of this sketch |
| datasketch_req_is_empty() | Object type: Scalar function | Return a boolean indicating if the sketch is empty |
| datasketch_req_is_estimation_mode() | Object type: Scalar function | Return a boolean indicating if the sketch is in estimation mode |
| datasketch_req_is_hra() | Object type: Scalar function | Return true if the sketch favors accuracy at high ranks (HRA), false if it favors low ranks (LRA) |
| datasketch_req_k() | Object type: Scalar function | Return the value of K for this sketch |
| datasketch_req_max_item() | Object type: Scalar function | Return the maximum item in the sketch |
| datasketch_req_min_item() | Object type: Scalar function | Return the minimum item in the sketch |
| datasketch_req_n() | Object type: Scalar function | Return the number of items contained in the sketch |
| datasketch_req_num_retained() | Object type: Scalar function | Return the number of retained items in the sketch |
| datasketch_req_pmf() | Object type: Scalar function | PMF (probability mass) over a list of split points β the fraction of the distribution falling in each bucket. |
| datasketch_req_quantile() | Object type: Scalar function | Approximate quantile at a given rank from a REQ sketch. |
| datasketch_req_quantiles() | Object type: Scalar function | Return the quantiles (items) at a list of normalized ranks in [0, 1]. |
| datasketch_req_rank() | Object type: Scalar function | Approximate rank of a value within the REQ sketch. |
| datasketch_req_rank_lower_bound() | Object type: Scalar function | Return an approximate lower bound of the given normalized rank, with a confidence of num_std_dev standard deviations (1, 2 or 3) |
| datasketch_req_rank_upper_bound() | Object type: Scalar function | Return an approximate upper bound of the given normalized rank, with a confidence of num_std_dev standard deviations (1, 2 or 3) |
| datasketch_req_ranks() | Object type: Scalar function | Return the normalized ranks of a list of items. |
| datasketch_req_sorted_view() | Object type: Scalar function | Return the sketch's sorted view: one entry per retained item in ascending order (equal items can appear more than once), with the item's weight and the inclusive cumulative weight (the number of input items less than or equal to it; estimated once the sketch is in estimation mode). |
|
TDigest
t-digest β quantile sketch optimized for the tails (p99, p999). Most accurate where SLOs live; FLOAT/DOUBLE input only. Use when tail latencies or outliers matter more than median accuracy. |
||
| datasketch_tdigest() | Object type: Aggregate function | Aggregate input values into a t-digest quantile sketch β most accurate at the tails (p99, p999), exactly where SLOs live. |
| datasketch_tdigest_cdf() | Object type: Scalar function | Return the Cumulative Distribution Function (CDF) of the sketch for a series of points |
| datasketch_tdigest_describe() | Object type: Scalar function | Return a description of this sketch |
| datasketch_tdigest_is_empty() | Object type: Scalar function | Return a boolean indicating if the sketch is empty |
| datasketch_tdigest_k() | Object type: Scalar function | Return the value of K for this sketch |
| datasketch_tdigest_max_value() | Object type: Scalar function | Exact maximum value seen by the t-digest. |
| datasketch_tdigest_min_value() | Object type: Scalar function | Exact minimum value seen by the t-digest. |
| datasketch_tdigest_pmf() | Object type: Scalar function | Return the Probability Mass Function (PMF) of the sketch for a series of points |
| datasketch_tdigest_quantile() | Object type: Scalar function | Approximate quantile at a given rank from a t-digest sketch. |
| datasketch_tdigest_rank() | Object type: Scalar function | Approximate rank of a value within the t-digest sketch. |
| datasketch_tdigest_total_weight() | Object type: Scalar function | Return the total weight of this sketch |
|
Theta
Theta sketch β the only distinct-count family that supports set operations beyond union. Combine cohorts with |
||
| datasketch_theta() | Object type: Aggregate function | Aggregate input values into a Theta sketch β the distinct-count family that supports set operations (union, intersect, A-not-B) beyond simple merge. |
| datasketch_theta_a_not_b() | Object type: Scalar function |
Approximate |A \ B| β distinct items present in A but not in B.
|
| datasketch_theta_blob() | Object type: Aggregate function | Hashes raw BLOB values (their bytes) into a Theta sketch, like datasketch_theta does for other types (datasketch_theta(BLOB) merges serialized sketches instead). |
| datasketch_theta_describe() | Object type: Scalar function | Returns a human-readable description of the Theta sketch |
| datasketch_theta_dissimilarity_test() | Object type: Scalar function | Returns true if the Jaccard similarity of the two sketches is at most the threshold, with high confidence (its upper bound is <= threshold) |
| datasketch_theta_estimate() | Object type: Scalar function | Read the estimated distinct count from a Theta sketch. |
| datasketch_theta_exactly_equal() | Object type: Scalar function | Returns true if the two sketches retain exactly the same hashes with the same theta, i.e. |
| datasketch_theta_get_seed() | Object type: Scalar function |
Alias of datasketch_theta_seed_hash: returns the 16-bit seed hash stored in the sketch (it always returned the hash, not the seed).
|
| datasketch_theta_get_theta() | Object type: Scalar function | Returns the theta value of the sketch (sampling probability) |
| datasketch_theta_intersect() | Object type: Scalar function |
Approximate |A β© B| β distinct items present in both cohorts.
|
| datasketch_theta_intersect_agg() | Object type: Aggregate function | Intersects Theta sketches across rows: the result estimates the number of distinct values present in every input sketch. |
| datasketch_theta_is_empty() | Object type: Scalar function | Returns true if the Theta sketch is empty |
| datasketch_theta_is_estimation_mode() | Object type: Scalar function | Returns true if the sketch is in estimation mode (has exceeded exact counting capacity) |
| datasketch_theta_jaccard() | Object type: Scalar function | Returns the Jaccard similarity |A β© B| / |A βͺ B| of two sketches as a struct of its estimate and approximate lower and upper bounds (about 2 standard deviations). |
| datasketch_theta_lower_bound() | Object type: Scalar function | Lower bound of the Theta distinct-count estimate. |
| datasketch_theta_num_retained() | Object type: Scalar function | Returns the number of hash values retained in the sketch |
| datasketch_theta_seed_hash() | Object type: Scalar function | Returns the 16-bit hash of the seed the sketch was built with (compact sketches store only this hash, not the seed); sketches can only be combined if their seed hashes match |
| datasketch_theta_similarity_test() | Object type: Scalar function | Returns true if the Jaccard similarity of the two sketches is at least the threshold, with high confidence (its lower bound is >= threshold) |
| datasketch_theta_union() | Object type: Scalar function |
Approximate |A βͺ B βͺ β¦| β scalar union of two or more Theta sketches.
|
| datasketch_theta_upper_bound() | Object type: Scalar function | Upper bound of the Theta distinct-count estimate. |
|
Tuple
Tuple sketch β a Theta sketch whose retained keys each carry a DOUBLE summary (sum, min, max or presence). Count distinct keys and aggregate a metric per key in one pass β distinct customers with their revenue β with the same union / intersect / A-not-B algebra as Theta. |
||
| datasketch_tuple() | Object type: Aggregate function |
Aggregate (key, value) rows into a Tuple sketch (sketch_tuple_double): a Theta sketch of the distinct keys in which every retained key carries a DOUBLE summary of its values.
|
| datasketch_tuple_a_not_b() | Object type: Scalar function | Returns a new Tuple sketch with the keys (and their summaries) of sketch A that are not in sketch B (set difference) |
| datasketch_tuple_describe() | Object type: Scalar function | Returns a human-readable description of the Tuple sketch |
| datasketch_tuple_dissimilarity_test() | Object type: Scalar function | Returns true if the Jaccard similarity of the key sets is at most the threshold, with high confidence (its upper bound is <= threshold) |
| datasketch_tuple_estimate() | Object type: Scalar function | Returns the estimated number of distinct keys in the Tuple sketch |
| datasketch_tuple_exactly_equal() | Object type: Scalar function | Returns true if the two sketches retain exactly the same keys with the same theta (summaries are not compared) |
| datasketch_tuple_get_theta() | Object type: Scalar function | Returns the theta value of the Tuple sketch (the fraction of the key hash space it retains) |
| datasketch_tuple_intersect() | Object type: Scalar function | Returns the intersection of two or more Tuple sketches: the keys present in every sketch, with their summaries combined by mode := 'sum' (default), 'min', 'max' or 'one' |
| datasketch_tuple_intersect_agg() | Object type: Aggregate function | Intersects Tuple sketches across rows: keeps the keys present in every sketch, combining their summaries by mode := 'sum' (default), 'min', 'max' or 'one'. |
| datasketch_tuple_is_empty() | Object type: Scalar function | Returns true if the Tuple sketch is empty |
| datasketch_tuple_is_estimation_mode() | Object type: Scalar function | Returns true if the Tuple sketch is in estimation mode (it has sampled the keys) |
| datasketch_tuple_jaccard() | Object type: Scalar function | Returns the Jaccard similarity of the key sets of two sketches as a struct of its estimate and approximate lower and upper bounds (about 2 standard deviations). |
| datasketch_tuple_lower_bound() | Object type: Scalar function | Returns the lower bound of the estimated number of distinct keys at the given number of standard deviations (1, 2, or 3) |
| datasketch_tuple_mean() | Object type: Scalar function | Returns the mean summary per distinct key (the mean of the retained summaries), or NULL if the sketch retains no entries |
| datasketch_tuple_num_retained() | Object type: Scalar function | Returns the number of entries (keys with their summaries) retained in the Tuple sketch |
| datasketch_tuple_seed_hash() | Object type: Scalar function | Returns the 16-bit hash of the seed the Tuple sketch was built with; sketches can only be combined if their seed hashes match |
| datasketch_tuple_similarity_test() | Object type: Scalar function | Returns true if the Jaccard similarity of the key sets is at least the threshold, with high confidence (its lower bound is >= threshold) |
| datasketch_tuple_sum() | Object type: Scalar function | Returns the estimated total of the summaries over all distinct keys: the sum of the retained summaries divided by theta (with mode 'sum', the estimated sum of the values; exact when the sketch is not in estimation mode) |
| datasketch_tuple_summaries() | Object type: Scalar function | Returns the retained entries of the Tuple sketch as a list of {hash, summary} structs (the key hash and its summary) |
| datasketch_tuple_to_theta() | Object type: Scalar function | Converts the Tuple sketch to a Theta sketch of its keys (dropping the summaries), usable with the datasketch_theta functions |
| datasketch_tuple_union() | Object type: Scalar function | Returns the union of two or more Tuple sketches, keeping as many entries as the largest input (at least lg_k 12); the summaries of a key are combined by mode := 'sum' (default), 'min', 'max' or 'one' |
| datasketch_tuple_upper_bound() | Object type: Scalar function | Returns the upper bound of the estimated number of distinct keys at the given number of standard deviations (1, 2, or 3) |
|
Types
|
||
| sketch_aod | Object type: Logical type | Logical type registered by this extension. |
| sketch_cpc | Object type: Logical type | Logical type registered by this extension. |
| sketch_frequent_items | Object type: Logical type | Logical type registered by this extension. |
| sketch_hll | Object type: Logical type | Logical type registered by this extension. |
| sketch_kll_bigint | Object type: Logical type | Logical type registered by this extension. |
| sketch_kll_double | Object type: Logical type | Logical type registered by this extension. |
| sketch_kll_float | Object type: Logical type | Logical type registered by this extension. |
| sketch_kll_integer | Object type: Logical type | Logical type registered by this extension. |
| sketch_kll_smallint | Object type: Logical type | Logical type registered by this extension. |
| sketch_kll_tinyint | Object type: Logical type | Logical type registered by this extension. |
| sketch_kll_ubigint | Object type: Logical type | Logical type registered by this extension. |
| sketch_kll_uinteger | Object type: Logical type | Logical type registered by this extension. |
| sketch_kll_usmallint | Object type: Logical type | Logical type registered by this extension. |
| sketch_kll_utinyint | Object type: Logical type | Logical type registered by this extension. |
| sketch_kll_varchar | Object type: Logical type | Logical type registered by this extension. |
| sketch_quantiles_bigint | Object type: Logical type | Logical type registered by this extension. |
| sketch_quantiles_double | Object type: Logical type | Logical type registered by this extension. |
| sketch_quantiles_float | Object type: Logical type | Logical type registered by this extension. |
| sketch_quantiles_integer | Object type: Logical type | Logical type registered by this extension. |
| sketch_quantiles_smallint | Object type: Logical type | Logical type registered by this extension. |
| sketch_quantiles_tinyint | Object type: Logical type | Logical type registered by this extension. |
| sketch_quantiles_ubigint | Object type: Logical type | Logical type registered by this extension. |
| sketch_quantiles_uinteger | Object type: Logical type | Logical type registered by this extension. |
| sketch_quantiles_usmallint | Object type: Logical type | Logical type registered by this extension. |
| sketch_quantiles_utinyint | Object type: Logical type | Logical type registered by this extension. |
| sketch_quantiles_varchar | Object type: Logical type | Logical type registered by this extension. |
| sketch_req_bigint | Object type: Logical type | Logical type registered by this extension. |
| sketch_req_double | Object type: Logical type | Logical type registered by this extension. |
| sketch_req_float | Object type: Logical type | Logical type registered by this extension. |
| sketch_req_integer | Object type: Logical type | Logical type registered by this extension. |
| sketch_req_smallint | Object type: Logical type | Logical type registered by this extension. |
| sketch_req_tinyint | Object type: Logical type | Logical type registered by this extension. |
| sketch_req_ubigint | Object type: Logical type | Logical type registered by this extension. |
| sketch_req_uinteger | Object type: Logical type | Logical type registered by this extension. |
| sketch_req_usmallint | Object type: Logical type | Logical type registered by this extension. |
| sketch_req_utinyint | Object type: Logical type | Logical type registered by this extension. |
| sketch_tdigest_double | Object type: Logical type | Logical type registered by this extension. |
| sketch_tdigest_float | Object type: Logical type | Logical type registered by this extension. |
| sketch_theta | Object type: Logical type | Logical type registered by this extension. |
| sketch_tuple_double | Object type: Logical type | Logical type registered by this extension. |
No extension contents match that search.
API Reference
Function Reference
Data model
Registered Types
Logical types this extension adds to DuckDB. Functions in the reference may accept or return these names directly.
-
sketch_aodLogical type registered by this extension.
-
sketch_cpcLogical type registered by this extension.
-
sketch_frequent_itemsLogical type registered by this extension.
-
sketch_hllLogical type registered by this extension.
-
sketch_kll_bigintLogical type registered by this extension.
-
sketch_kll_doubleLogical type registered by this extension.
-
sketch_kll_floatLogical type registered by this extension.
-
sketch_kll_integerLogical type registered by this extension.
-
sketch_kll_smallintLogical type registered by this extension.
-
sketch_kll_tinyintLogical type registered by this extension.
-
sketch_kll_ubigintLogical type registered by this extension.
-
sketch_kll_uintegerLogical type registered by this extension.
-
sketch_kll_usmallintLogical type registered by this extension.
-
sketch_kll_utinyintLogical type registered by this extension.
-
sketch_kll_varcharLogical type registered by this extension.
-
sketch_quantiles_bigintLogical type registered by this extension.
-
sketch_quantiles_doubleLogical type registered by this extension.
-
sketch_quantiles_floatLogical type registered by this extension.
-
sketch_quantiles_integerLogical type registered by this extension.
-
sketch_quantiles_smallintLogical type registered by this extension.
-
sketch_quantiles_tinyintLogical type registered by this extension.
-
sketch_quantiles_ubigintLogical type registered by this extension.
-
sketch_quantiles_uintegerLogical type registered by this extension.
-
sketch_quantiles_usmallintLogical type registered by this extension.
-
sketch_quantiles_utinyintLogical type registered by this extension.
-
sketch_quantiles_varcharLogical type registered by this extension.
-
sketch_req_bigintLogical type registered by this extension.
-
sketch_req_doubleLogical type registered by this extension.
-
sketch_req_floatLogical type registered by this extension.
-
sketch_req_integerLogical type registered by this extension.
-
sketch_req_smallintLogical type registered by this extension.
-
sketch_req_tinyintLogical type registered by this extension.
-
sketch_req_ubigintLogical type registered by this extension.
-
sketch_req_uintegerLogical type registered by this extension.
-
sketch_req_usmallintLogical type registered by this extension.
-
sketch_req_utinyintLogical type registered by this extension.
-
sketch_tdigest_doubleLogical type registered by this extension.
-
sketch_tdigest_floatLogical type registered by this extension.
-
sketch_thetaLogical type registered by this extension.
-
sketch_tuple_doubleLogical type registered by this extension.
Practical Examples
Cookbook
Real-world recipes and patterns for common use cases.
Recipes for distinct counts, quantiles, and heavy hitters with Apache DataSketches.
Distinct count with HLL
The bread-and-butter sketch β approximate COUNT(DISTINCT) in a few KB of memory.
SELECT datasketch_hll_estimate(datasketch_hll(12, user_id)) AS distinct_usersFROM events;user_id can be any integer, float, string, blob, UUID, HUGEINT, or UHUGEINT column. The 12 is lg_k β base-2 log of the bucket count. lg_k = 12 (4096 buckets, ~4 KB sketch, ~1.6% standard error) is a common default. Bracket the estimate with datasketch_hll_lower_bound / datasketch_hll_upper_bound when you want a confidence interval; their second argument is num_std_devs β 1, 2, or 3 (β68%, 95%, 99.7%).
Per-day HLL sketches, rolled up on demand
Build the sketch state once; query any window without rescanning.
CREATE OR REPLACE TABLE daily_uniques (day DATE, hll sketch_hll);
INSERT INTO daily_uniquesSELECT date_trunc('day', ts) AS day, datasketch_hll(12, user_id) AS hllFROM eventsGROUP BY 1;
-- Rolling 7-day uniques β reads sketch state, not source eventsSELECT datasketch_hll_estimate(datasketch_hll_union(12, hll)) AS uniques_last_7dFROM daily_uniquesWHERE day >= CURRENT_DATE + INTERVAL '-7 days';The same pattern works for datasketch_cpc (smaller on disk, slower to write) and datasketch_theta (supports set operations beyond union).
Set operations with Theta β funnel, retention, churn
Theta is the only distinct-count family with full set algebra.
WITH a AS (SELECT datasketch_theta(12, user_id) AS s FROM events_jan), b AS (SELECT datasketch_theta(12, user_id) AS s FROM events_feb)SELECT datasketch_theta_estimate(datasketch_theta_union(a.s, b.s)) AS jan_or_feb, datasketch_theta_estimate(datasketch_theta_intersect(a.s, b.s)) AS retained, -- in both datasketch_theta_estimate(datasketch_theta_a_not_b(a.s, b.s)) AS churned, -- jan not feb datasketch_theta_estimate(datasketch_theta_a_not_b(b.s, a.s)) AS new_users -- feb not janFROM a, b;This is the headline use case for Theta β funnel and cohort analysis directly off sketch state. datasketch_theta_union and datasketch_theta_intersect take two or more sketches, and datasketch_theta_intersect_agg intersects a whole column of them.
How similar are two audiences? β Theta Jaccard
WITH a AS (SELECT datasketch_theta(12, user_id) AS s FROM events_jan), b AS (SELECT datasketch_theta(12, user_id) AS s FROM events_feb)SELECT datasketch_theta_jaccard(a.s, b.s) AS jaccard, -- {lower, estimate, upper} datasketch_theta_similarity_test(a.s, b.s, 0.3) AS at_least_30pctFROM a, b;Output
| jaccard | at_least_30pct |
|---|---|
| {'lower': 0.42857142857142855, 'estimate': 0.42857142857142855, 'upper': 0.42857142857142855} | true |
datasketch_theta_jaccard returns |A β© B| / |A βͺ B| with approximate bounds; the similarity / dissimilarity tests answer βat least / at most this similarβ with high confidence.
Distinct customers and their revenue β Tuple sketch
A Tuple sketch is a Theta sketch whose keys carry a value, so one pass counts distinct keys and aggregates a metric per key.
SELECT datasketch_tuple_estimate(s) AS customers, datasketch_tuple_sum(s) AS revenue, datasketch_tuple_mean(s) AS revenue_per_customerFROM (SELECT datasketch_tuple(customer_id, amount) AS s FROM orders);Output
| customers | revenue | revenue_per_customer |
|---|---|---|
| 40 | 19494 | 487.35 |
mode := 'min' | 'max' | 'one' changes how a keyβs values combine (the default is 'sum'). Tuple sketches merge, union, intersect and diff like Theta sketches β e.g. the revenue of customers present in two segments is datasketch_tuple_sum(datasketch_tuple_intersect(a, b)). For several metrics per key, use the array-of-doubles sketch:
SELECT datasketch_aod_column_sums(s) AS totals, -- [revenue, items] datasketch_aod_column_means(s) AS per_customerFROM (SELECT datasketch_aod(customer_id, [amount, items]) AS s FROM orders);Output
| totals | per_customer |
|---|---|
| [19494.0, 799.0] | [487.35, 19.975] |
p50 / p95 / p99 with KLL
KLL is the recommended general-purpose quantile sketch.
WITH agg AS ( SELECT datasketch_kll(200, latency_ms) AS sketch FROM requests)SELECT datasketch_kll_quantile(sketch, 0.50, true) AS p50, datasketch_kll_quantile(sketch, 0.95, true) AS p95, datasketch_kll_quantile(sketch, 0.99, true) AS p99FROM agg;Or ask for several quantiles in one call with datasketch_kll_quantiles β datasketch_kll_quantiles(sketch, [0.5, 0.95, 0.99], true) returns a list β and the reverse with datasketch_kll_ranks. K = 200 is a sensible production starting point. Higher K β smaller error, larger sketch. The trailing true is the inclusive flag β true for inclusive search (P[X β€ q]), false for exclusive (P[X < q]). Use datasketch_kll_normalized_rank_error to inspect the actual rank-error guarantee for the configured K.
Histograms in one query β KLL CDF / PMF
Get the cumulative distribution at any set of split points without a second pass.
SELECT datasketch_kll_cdf( datasketch_kll(200, latency_ms), [10, 50, 100, 250, 500, 1000], /* inclusive */ true ) AS cdfFROM requests;Returns a LIST(DOUBLE) of cumulative ranks, one per split point plus a final 1.0 β directly usable for histograms. CDF and PMF results are always DOUBLE, whatever the sketchβs item type. For the retained items themselves, with their weights, use datasketch_kll_sorted_view. Swap cdf for datasketch_kll_pmf to get per-bucket probability mass instead.
Tail-accurate quantiles with TDigest
When p99 / p999 matters more than the median (SLO reporting), reach for t-digest.
CREATE OR REPLACE TABLE readings(temp DOUBLE);INSERT INTO readings(temp) SELECT unnest(generate_series(1, 10))::DOUBLE;
-- Rank of value 5 within the aggregated sketchSELECT datasketch_tdigest_rank(datasketch_tdigest(100, temp), 5) AS rank_of_5FROM readings;Output
| rank_of_5 |
|---|
| 0.45 |
CDF over multiple split points in one call:
SELECT datasketch_tdigest_cdf(datasketch_tdigest(100, temp), [1, 5, 9]) AS cdfFROM readings;Output
| cdf |
|---|
| [0.0357, 0.3214, 0.6071, 1.0] |
TDigest accepts FLOAT/DOUBLE only. For integer or skewed-rank quantile work, see datasketch_kll or datasketch_req.
Top-K heavy hitters with Frequent Items
Find the most frequent items in a stream β with confidence bounds on each estimate.
SELECT datasketch_frequent_items_get_frequent( datasketch_frequent_items(8, country_code), 'NO_FALSE_POSITIVES' ) AS heavy_hittersFROM page_views;The result is a list of structs β (item, estimate, lower_bound, upper_bound). Use 'NO_FALSE_POSITIVES' for items that are definitely heavy hitters, 'NO_FALSE_NEGATIVES' for the union of all candidates that might be. The leading 8 is lg_max_k β logβ of the maximum number of tracked items (so 8 β up to 256 candidates). Bigger values track more candidates and tighten the per-item error bound; valid values are 3β30 and typical values run 4β12.
Skew-aware quantiles with REQ
When the distribution is heavily skewed and you want predictable accuracy across the whole rank space, REQ scales its error with rank rather than fixing it.
SELECT datasketch_req_quantile(datasketch_req(12, value), 0.001, true) AS p001, datasketch_req_quantile(datasketch_req(12, value), 0.5, true) AS p50, datasketch_req_quantile(datasketch_req(12, value), 0.999, true) AS p999FROM measurements;Persist sketches to Parquet, merge in another DuckDB
Sketch BLOBs are portable across processes and across DuckDB instances:
COPY (SELECT day, hll FROM daily_uniques) TO 'daily_uniques.parquet' (FORMAT PARQUET);
-- Later, anywhere with this extension loaded:SELECT datasketch_hll_estimate(datasketch_hll_union(12, hll))FROM read_parquet('daily_uniques.parquet')WHERE day BETWEEN DATE '2026-01-01' AND DATE '2026-01-31';The serialization format is the same one used by Druid, Pinot, BigQuery, and the Apache DataSketches Java library β sketches built here can be merged in those systems and vice versa.
Platform Support
Compatibility
Extension availability may vary by platform and DuckDB version. Check below to ensure this extension supports your environment before installation.
Quick Facts
Platforms
DuckDB 2.0.0
- Linux x86_64aarch64
- Linux (musl) Not available
- macOS Apple Silicon
- Windows x86_64x86_64 (MinGW)
- WASM Not available
Compiled binary sizes
| Platform | Architecture | Size |
|---|---|---|
| Linux | x86_64 | 6.10 MB |
| Linux | aarch64 | 5.11 MB |
| macOS | Apple Silicon | 4.50 MB |
| Windows | x86_64 | 11.61 MB |
| Windows | x86_64 (MinGW) | 19.79 MB |
Compressed download sizes for the release shown above.
DuckDB & Haybarn
Release calendar- DuckDB v2.0.0 Query.Farm repository Supported
- Haybarn v1.5.6 Built-in community repository Supported
Browser examples use Haybarn-Wasm 2.0.0-rc12.
Checked .
Learn and explore
Tutorials and articles
Writing about Apache DataSketches: how it works, what changed, and why.
-
Tutorial Β· 7 min Β·
Count Weekly Unique Visitors: Why Daily Counts Donβt Add Up
Compare exact distinct counts with mergeable HLL sketches in DuckDB. See why daily unique counts overcount a longer period, with runnable DataSketches examples.
-
Tutorial Β· 7 min Β·
Calculate Overall p95 Latency Without Averaging Percentiles
Calculate an exact pooled percentile in DuckDB, see why weighted regional percentiles fail, and merge KLL sketches with the DataSketches extension.
-
DataSketches for DuckDB 2.0: sketch aggregates now stay within the memory limit and spill to disk
A grouped KLL query used 39 GB under a 1 GB memory limit. Now it uses 0.77 GB and runs 3.7Γ faster. Here's how we moved 15 sketch families into DuckDB's spillable memory, and the library bugs we fixed along the way.