Skip to content

Medians and percentiles

Compute medians, quartiles and p90 with PERCENTILE_CONT, and know when an average hides the real story.

Practise: 5 questions

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:

  1. Compute the value you want to take a percentile of at the right grain (for example, hours per ticket).
  2. Use percentile_cont(p) within group (order by value). The fraction p is between 0 and 1.
  3. Group as usual. It is an aggregate in PostgreSQL.
  4. 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

Variations

In other warehouses

Practise medians and percentiles