SQL Aggregate Functions, Percentiles, DISTINCT, and Approximate Summaries
How to count, sum, average, find percentiles and top values with GROUP BY, DISTINCT, and approximate aggregates in analytics SQL.
This page summarizes Cloudflare documentation on aggregate functions in Workers Analytics Engine SQL, Basin SQL (R2 SQL), and the broader Analytics SQL API. Aggregates answer questions such as how many events occurred, what the p95 latency was, or which values appear most often—usually with GROUP BY for per-dimension summaries.
Aggregate functions and GROUP BY: how row summaries work
Section titled “Aggregate functions and GROUP BY: how row summaries work”Aggregate functions collapse multiple input rows into one value per group (or one value for the whole result set when you omit GROUP BY).
Aggregate functions collapse multiple rows into a single result. They are used with GROUP BY to compute summaries per group, or without GROUP BY to compute a single result across all rows.
— Cloudflare, Aggregate functions
Basin SQL expresses the same idea in its query syntax: SELECT may list columns, expressions, aggregate_function, or window_function, with optional GROUP BY and HAVING. Workers Analytics Engine supports aggregates in SELECT (including inside a FROM subquery on a single table). The Analytics SQL API documents which aggregates each dataset backend supports (ClickHouse-backed, Log Explorer, Workers Analytics Engine, state datasets).
COUNT, SUM, and AVG: basic totals and averages
Section titled “COUNT, SUM, and AVG: basic totals and averages”COUNT answers “how many rows?” (or how many non-null values in a column). SUM and AVG answer “what is the total?” and “what is the mean?” on numeric columns.
On Basin SQL:
Counts rows. COUNT(*) counts all rows. COUNT(column) counts non-NULL values.
— Cloudflare, Aggregate functions
On Workers Analytics Engine, count() returns the number of rows in each group or result set; sum, avg, and max follow the usual SQL meanings:
count is an aggregation function that returns the number of rows in each group or results set.
— Cloudflare, Aggregate functions
The Analytics SQL API notes that COUNT(*) or COUNT() count matching rows or represented events, and that COUNT(expression) is not supported on that API—unlike Basin SQL’s COUNT(column).
Log Explorer documents the same familiar pattern for log datasets: SUM, MIN, MAX, COUNT, COUNT(DISTINCT ...), and AVG with GROUP BY for grouped reports.
MIN and MAX: exact and approximate extrema
Section titled “MIN and MAX: exact and approximate extrema”Basin SQL provides exact max(column_name) (and the reference covers the same family for minimums in the broader SQL surface). The Analytics SQL API distinguishes exact MIN/MAX on unsampled data from APPROX_MIN / APPROX_MAX on adaptively sampled datasets—use approximates when the backend retains only a sample of rows.
DISTINCT in aggregates: unique counts and de-duplicated sums
Section titled “DISTINCT in aggregates: unique counts and de-duplicated sums”Many readers search for “count unique” or COUNT(DISTINCT ...). Cloudflare products treat DISTINCT inside aggregates differently.
DISTINCT modifier on COUNT, SUM, and AVG
Section titled “DISTINCT modifier on COUNT, SUM, and AVG”Basin SQL states that most aggregates accept DISTINCT:
Most aggregates accept a DISTINCT modifier, for example COUNT(DISTINCT customer_id) or SUM(DISTINCT total_amount).
— Cloudflare, Aggregate functions
Workers Analytics Engine documents the forms explicitly:
count(DISTINCT column_name)sum(DISTINCT item_cost)avg(DISTINCT item_cost)— see Aggregate functions.
For row-level uniqueness (not inside an aggregate), Basin SQL also supports SELECT DISTINCT and notes that on large datasets approx_distinct() is faster for counting unique values—see SELECT DISTINCT changelog.
Analytics SQL API: which DISTINCT forms work per backend
Section titled “Analytics SQL API: which DISTINCT forms work per backend”The SQL API functions reference splits support by dataset type:
The following forms are supported by ClickHouse-backed unsampled datasets: COUNT(DISTINCT expression), SUM(DISTINCT expression), AVG(DISTINCT expression). Other DISTINCT aggregates and row-level SELECT DISTINCT are not supported. Adaptively sampled datasets reject DISTINCT aggregates because omitted values cannot be reconstructed. Workers Analytics Engine datasets retain COUNT, SUM, and AVG DISTINCT for compatibility. Log Explorer-backed datasets support COUNT(DISTINCT expression) and SUM(DISTINCT expression), but not AVG(DISTINCT expression).
— Cloudflare, DISTINCT aggregates
Common conclusion: use COUNT(DISTINCT ...) when you need exact unique counts on supported backends; on large Basin SQL tables or when the API allows approximations, prefer approx_distinct() for speed; never use DISTINCT aggregates on adaptively sampled Analytics SQL API datasets.
Conditional aggregates: countIf and sumIf
Section titled “Conditional aggregates: countIf and sumIf”When people ask “how many rows match a condition?” or “sum this column only when another flag is set,” conditional aggregates avoid extra subqueries.
Workers Analytics Engine:
countIf is an aggregation function that returns the number of rows in the results set, but only counting rows where a provided expression evaluates to true.
— Cloudflare, Aggregate functions
Example from the same page: countIf(double1 > 5). sumIf(<expr>, <expr>) sums the first expression only where the second is true (e.g. sumIf(item_cost, in_stock > 0)).
The Analytics SQL API lists compatible forms countIf, sumIf, and avgIf on ClickHouse-backed datasets, and notes that state datasets require the corresponding base aggregation (count, sum, or avg) to appear in that dataset’s valid_aggregations list—see State datasets.
Percentiles and median: exact vs approximate
Section titled “Percentiles and median: exact vs approximate”Latency and revenue questions often need medians or p95/p99—not just averages.
Exact percentiles on Basin SQL
Section titled “Exact percentiles on Basin SQL”Returns the exact median value. For large datasets, use approx_median instead.
— Cloudflare, MEDIAN
PERCENTILE_CONT returns the exact value at a percentile between 0.0 and 1.0 using WITHIN GROUP (ORDER BY ...); PERCENTILE_DISC is not supported—use PERCENTILE_CONT or approx_percentile_cont instead (same reference).
Weighted quantiles on Workers Analytics Engine
Section titled “Weighted quantiles on Workers Analytics Engine”Sampled Analytics Engine data often uses a weight column such as _sample_interval:
quantileExactWeighted is an aggregation function that returns the value at the qth quantile in the named column across all rows in each group or results set. Each row will be weighted by the value in weight_column_name. Typically this would be _sample_interval (refer to Sampling for more information).
— Cloudflare, Aggregate functions
Example: quantileExactWeighted(0.95)(query_time, _sample_interval). The alias quantileWeighted(q, column_name, weight_column_name) remains for compatibility.
Approximate percentiles, median, and distinct (Basin SQL / R2 SQL)
Section titled “Approximate percentiles, median, and distinct (Basin SQL / R2 SQL)”Approximate aggregation functions produce statistically estimated results while using significantly less memory and compute than their exact counterparts. Use them when analyzing large datasets and an approximate result is acceptable.
— Cloudflare, Approximate aggregates
| Function | Role |
|---|---|
approx_percentile_cont(column, percentile) |
Approximate value at percentile (T-Digest); 0.0–1.0 |
approx_percentile_cont_with_weight(column, weight, percentile) |
Weighted approximate percentile |
approx_median(column) |
Same as approx_percentile_cont(column, 0.5) |
approx_distinct(column) |
Approximate distinct count (HyperLogLog) |
approx_top_k(column, k) |
Top k frequent values with approximate counts |
Changelog entries for R2 SQL describe the same family: approximate aggregation functions. All listed approximate functions support WHERE; all except approx_top_k support GROUP BY per that changelog.
Limitations and best practices recommend approximate alternatives on large datasets and note that MEDIAN, PERCENTILE_CONT, aggregates with DISTINCT, and window functions used through QUALIFY are budget-gated—Basin SQL may reject a query with HTTP 400 if estimated memory is too high.
topK and frequent values: exact and weighted ranks
Section titled “topK and frequent values: exact and weighted ranks”“What are the most common status codes or URLs?” maps to top-K aggregates.
Workers Analytics Engine topK(N)(column) returns the most common N values (N defaults to 10). topKWeighted(N)(column, weight_column) weights counts (often with _sample_interval). The Analytics SQL API adds parameter limits: requested top-k size and load factor must each be between 1 and 100—see Aggregate functions.
Basin SQL offers approx_top_k(column, k), returning frequent values as a JSON array with approximate counts (aggregate reference, changelog examples).
Aggregates with JOINs, HAVING, and collection functions
Section titled “Aggregates with JOINs, HAVING, and collection functions”Basin SQL supports multi-table queries with aggregates—for example counting requests per zone after an INNER JOIN (joins changelog). Use HAVING to filter groups after aggregation (e.g. HAVING COUNT(*) > 1000 in the SQL reference).
ARRAY_AGG and STRING_AGG are exact collection aggregates mentioned in window and set-operation changelogs. The aggregate reference warns that collection aggregates hold values in memory—bound group size with WHERE or GROUP BY on large tables (Collection aggregates).
Workers Analytics Engine FROM still allows only a single table (no UNION/JOIN in statements); use subqueries in FROM for one-table reshaping before aggregating.
Common mistakes when aggregating analytics SQL
Section titled “Common mistakes when aggregating analytics SQL”- Using
COUNT(column)on the Analytics SQL API where onlyCOUNT(*)is valid—check Functions. DISTINCTaggregates on sampled datasets—rejected on adaptively sampled Analytics SQL API data (DISTINCT aggregates).- Exact median/percentile on huge tables—prefer
approx_median/approx_percentile_contper Basin SQL aggregates and limitations. - Heavy
COUNT(DISTINCT)after joins—timeout risk; see troubleshooting. - Unbounded
ARRAY_AGG/STRING_AGG—memory growth on large groups (Collection aggregates). - Assuming Log Explorer equals Basin SQL—Log Explorer documents a smaller aggregate and expression set (SQL queries supported).
How to check this on your site
Section titled “How to check this on your site”-
Identify your engine: Workers Analytics Engine SQL API, Basin SQL, or Analytics SQL API / Log Explorer—each has different aggregate support.
-
Run a smoke test with
COUNT(*)and one dimension: e.g.SELECT department, COUNT(*) AS dept_count FROM my_namespace.sales_data GROUP BY department ORDER BY dept_count DESCfrom Basin SQL COUNT. -
If the query is slow or rejected with HTTP 400, retry with
approx_distinct,approx_median, orapprox_percentile_contand addWHERE/LIMITper Limitations and best practices and troubleshooting. -
For Analytics SQL API datasets, confirm
DISTINCTand conditional aggregates against the backend table in Functions (unsupported syntax returns HTTP 422). -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page does not match the official docs or your query results, email yimasynthetic@gmail.com with the page URL and the exact wording you believe is wrong so it can be corrected or clarified.