When you need it
"Median order value", "p90 time to first response", "typical salary by department", "what is the 95th percentile of load time". Words that signal it: "median", "percentile", "p50", "p90", "typical", "middle", "quartile", "distribution".
The average is pulled around by a few huge values. The median is the middle value and does not care how large the top is. Support times, order sizes and salaries are all skewed, so analysts quote medians.
The shape of the query
select group_col,
percentile_cont(0.5) within group (order by value) as median,
percentile_cont(0.9) within group (order by value) as p90
from t
group by group_col;Step by step:
- Compute the value you want to take a percentile of at the right grain (for example, hours per ticket).
- Use
percentile_cont(p) within group (order by value). The fractionpis between 0 and 1. - Group as usual. It is an aggregate in PostgreSQL.
- Round the result if the prompt says so.
select priority,
count(*) as tickets,
round(avg(extract(epoch from (first_response_at - created_at)) / 60.0)::numeric, 1) as avg_minutes,
round((percentile_cont(0.5) within group (
order by extract(epoch from (first_response_at - created_at)) / 60.0))::numeric, 1) as median_minutes,
round((percentile_cont(0.9) within group (
order by extract(epoch from (first_response_at - created_at)) / 60.0))::numeric, 1) as p90_minutes
from tickets
where first_response_at is not null
group by priority
order by priority;Comparing the average with the median in the same row shows right away how skewed the data is.
percentile_disc returns an actual value from the data (the first one at or above the percentile) instead of interpolating:
select department_id,
count(*) as people,
percentile_cont(0.5) within group (order by salary) as median_salary,
percentile_disc(0.5) within group (order by salary) as median_salary_disc
from employees
where termination_date is null and department_id is not null
group by department_id
order by department_id;Traps interviewers look for
- Even counts. The median of 1, 2, 3, 4 is 2.5 with
percentile_cont(it interpolates) and 2 withpercentile_disc. Know which the prompt wants. "Median" in most definitions is the interpolated one. - NULLs. Percentile functions skip NULLs. Say whether missing values should be dropped or count as something. A ticket with no response yet should not become zero minutes.
- Median of medians. The median of group medians is not the overall median. Compute from the raw rows.
- Averaging percentiles. Do not average p90 across days to get a monthly p90.
- Group size. A percentile of 3 rows is not meaningful. If the prompt includes a minimum group size, filter with
having count(*) >= n. - Percentile on a non-numeric column.
percentile_contneeds numbers or intervals. For dates, convert to a number such as an epoch. - No window syntax needed. In PostgreSQL this is an ordered-set aggregate, not a window function. Do not add
over.
Variations
- Quartiles and IQR.
percentile_cont(array[0.25, 0.5, 0.75]) within group (order by x)returns an array. Or call it three times. - Median by manual method. Number rows with
row_numberandcount(*) over (), then average the middle one or two rows. Interviewers may ask for it when functions are banned. NTILE.ntile(100)orntile(4)assigns each row to a bucket.- Outlier trimming. Compute p1 and p99, then filter to between them.
- Percentile rank of a row.
percent_rank() over (order by x)gives the relative position of each row.
In other warehouses
- Snowflake and Redshift have the same
percentile_cont(...) within group (order by ...)aggregate, and aMEDIAN(x)shortcut. Databricks also hasmedian(x)andpercentile_cont. - BigQuery has
PERCENTILE_CONT(x, 0.5) OVER ()only as a window function, so it needsOVER (PARTITION BY group)andSELECT DISTINCTto get one row per group. For an approximate answer,APPROX_QUANTILES(x, 100)[OFFSET(50)]. - SQL Server also has
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) OVER (PARTITION BY group), window form only. - MySQL has no built-in percentile function. Use the row number method.