SQL Dojo
Keyword

Median and percentiles

The median and other percentiles in SQL, with PERCENTILE_CONT, PERCENTILE_DISC or MEDIAN: the typical value an average hides when a few rows are huge.

Take the median when a few big values pull the average up: the typical basket, the typical salary, the usual delivery time. A percentile generalises it: p90 is the value that 90 % of the rows stay at or under.

SELECT AVG(salary) AS mean,
       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median,
       PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY salary) AS p90
FROM employees;

PERCENTILE_CONT interpolates between the two middle rows (the median of 10 and 20 is 15); PERCENTILE_DISC returns an actual value of the column (10). Add a GROUP BY for one median per group.

The trap. A median does not add up. The average of the daily medians is not the month's median, and neither is the median of the per-store medians: compute it from the detail rows, every time.

On your warehouse. Postgres has the WITHIN GROUP form only, no MEDIAN. Snowflake also has MEDIAN(x) and APPROX_PERCENTILE(x, 0.9). BigQuery has no aggregate form: PERCENTILE_CONT(salary, 0.5) OVER () is a window function, and a GROUP BY uses APPROX_QUANTILES(salary, 100)[OFFSET(50)], an approximation. Databricks has median(x), percentile(x, 0.9) and percentile_approx(x, 0.9). DuckDB has MEDIAN(x) and quantile_cont(x, 0.9).

SELECT ROUND(AVG(salary), 2) AS mean,
       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median,
       PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY salary) AS p90,
       PERCENTILE_DISC(0.9) WITHIN GROUP (ORDER BY salary) AS p90_disc
FROM employees;
meanmedianp90p90_disc
2835.02600.004110.004100.00
Try it in Randori