BigQuery · Aggregate function
BigQuery APPROX_QUANTILES
APPROX_QUANTILES(x, n) returns an array of n + 1 approximate quantile boundaries, from the minimum to the maximum. APPROX_QUANTILES(x, 100)[OFFSET(50)] is the median and [OFFSET(95)] the 95th percentile; unlike PERCENTILE_CONT it works in GROUP BY queries.
APPROX_QUANTILES returns number + 1 values in ascending order: the approximate minimum, the boundaries between number equal-sized buckets, and the approximate maximum. With number = 100, element [OFFSET(p)] is the p-th percentile, so a single call gives the median, p90 and p99 together. NULLs are ignored unless you add RESPECT NULLS.
Every boundary is a value from the input, never an interpolation between two values. For an even number of rows, the median is one of the two middle values, while the textbook median, as computed by PERCENTILE_CONT, averages them. On large inputs the result is an estimate. For an exact percentile use PERCENTILE_CONT or PERCENTILE_DISC, which are window functions and need each partition's rows in one place.
BigQuery has no MEDIAN or PERCENTILE aggregate, and PostgreSQL's PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) is a syntax error, so APPROX_QUANTILES is the usual way to get percentiles per group. Google's performance guide also recommends it over NTILE for bucketing large tables, because NTILE needs a global sort on one worker.
Syntax
APPROX_QUANTILES([DISTINCT] expression, number [{IGNORE | RESPECT} NULLS] [WHERE where_expression])Arguments and return value
| Argument | Description |
|---|---|
expression | Any type except ARRAY, STRUCT and INTERVAL: numbers, strings, dates and timestamps all work. |
number | How many quantiles to divide the data into. An INT64 literal or query parameter, not a column. The result has number + 1 elements. |
DISTINCT | Computes the quantiles over distinct values only. |
IGNORE NULLS | RESPECT NULLS | NULLs are ignored by default. With RESPECT NULLS they are included and sort first, so the lowest boundaries can be NULL. |
WHERE where_expression | Optional filter inside the call (Preview). It requires IGNORE NULLS. |
Returns: ARRAY of the expression's type with number + 1 elements. NULL when there are no rows or every value is NULL.
Examples
Median, p90 and maximum latency from one call
The single 2,500 ms outlier pulls the average far above the median.
SELECT
q[OFFSET(50)] AS p50_ms,
q[OFFSET(90)] AS p90_ms,
q[OFFSET(100)] AS max_ms,
avg_ms
FROM (
SELECT
APPROX_QUANTILES(latency_ms, 100) AS q,
AVG(latency_ms) AS avg_ms
FROM UNNEST([120, 85, 300, 95, 110, 2500, 140, 105, 90, 130]) AS latency_ms
);| p50_ms | p90_ms | max_ms | avg_ms |
|---|---|---|---|
| 110 | 300 | 2500 | 367.5 |
Median per group
WITH requests AS (
SELECT 'checkout' AS endpoint, 180 AS latency_ms UNION ALL
SELECT 'checkout', 220 UNION ALL
SELECT 'checkout', 950 UNION ALL
SELECT 'search', 40 UNION ALL
SELECT 'search', 55 UNION ALL
SELECT 'search', 60
)
SELECT
endpoint,
APPROX_QUANTILES(latency_ms, 2)[OFFSET(1)] AS median_ms,
COUNT(*) AS requests
FROM requests
GROUP BY endpoint
ORDER BY endpoint;| endpoint | median_ms | requests |
|---|---|---|
| checkout | 220 | 3 |
| search | 55 | 3 |
Quartiles, and no interpolation
Four quantiles give five values: minimum, Q1, median, Q3 and maximum. The median is 40, one of the two middle values; PERCENTILE_CONT would return 44, their average.
SELECT APPROX_QUANTILES(order_value, 4) AS quartiles
FROM UNNEST([12, 25, 31, 40, 48, 55, 70, 90]) AS order_value;| quartiles |
|---|
| [12, 25, 40, 55, 90] |
RESPECT NULLS
With RESPECT NULLS the two NULLs sort first and become the minimum. An array containing NULL can't be returned directly, so FORMAT prints it as text.
SELECT
APPROX_QUANTILES(score, 2) AS ignore_nulls,
FORMAT('%T', APPROX_QUANTILES(score, 2 RESPECT NULLS)) AS respect_nulls
FROM UNNEST([NULL, NULL, 3, 7, 9]) AS score;| ignore_nulls | respect_nulls |
|---|---|
| [3, 7, 9] | [NULL, 3, 9] |
Common mistakes
- Using ORDINAL instead of OFFSET.
APPROX_QUANTILES(x, 100)[OFFSET(50)]is the median;[ORDINAL(50)]is the 49th percentile, because ORDINAL counts from 1. - Forgetting the extra element.
APPROX_QUANTILES(x, 4)returns five values, so the median is[OFFSET(2)]and the maximum[OFFSET(4)]. - Expecting an interpolated median. The function returns observed values; for 10, 20, 30, 40 the median is 20 or 30, not 25.
- Passing a column as
number. It fails withArgument 2 to APPROX_QUANTILES must be a literal or query parameter. - Adding OVER.
APPROX_QUANTILES(x, 100) OVER (...)fails withAnalytic function APPROX_QUANTILES is not supported. Compute the quantiles in a GROUP BY subquery and join them back.
Cost and performance
- An exact percentile with
PERCENTILE_CONT(x, 0.5) OVER ()makes the whole table a single window partition, which one worker has to process; on large tables that can fail with Resources exceeded. APPROX_QUANTILES is an ordinary aggregate and runs in parallel. Both read the same column, so bytes billed are the same.
FAQ
How do I calculate the median in BigQuery?
In a GROUP BY query, APPROX_QUANTILES(x, 2)[OFFSET(1)] or APPROX_QUANTILES(x, 100)[OFFSET(50)]. For an exact, interpolated median use PERCENTILE_CONT(x, 0.5) OVER (PARTITION BY ...) with SELECT DISTINCT. There is no MEDIAN function.
How do I calculate p95 or p99 latency?
Take APPROX_QUANTILES(latency_ms, 100) once and pick [OFFSET(95)] and [OFFSET(99)] from the array. For finer percentiles such as p99.9, use 1000 quantiles and [OFFSET(999)].
What is the difference between APPROX_QUANTILES and PERCENTILE_CONT?
APPROX_QUANTILES is an aggregate: it works with GROUP BY, scales to large tables and returns observed values, approximately. PERCENTILE_CONT is an exact window function that interpolates between values and needs each partition in one place.
Related
Errors you may hit
More aggregate functions
All BigQuery aggregate functions · All functions · BigQuery error messages
