Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 08 / Topic 8 of 10

Medians and percentiles

avg is famously draggable by outliers; the median isn't. SQL spells it as a percentile — with two flavours:

SELECT round(avg(price), 2) AS average,
       percentile_cont(0.5) WITHIN GROUP (ORDER BY price) AS median_cont,
       percentile_disc(0.5) WITHIN GROUP (ORDER BY price) AS median_disc
FROM products;
 average | median_cont | median_disc 
---------+-------------+-------------
  369.80 |         100 |       80.00
(1 row)
  • percentile_cont interpolates between the two middle values when the count is even — a value that may not exist in the data.
  • percentile_disc returns an actual value from the data.

(Postgres has no median() function — this is the spelling.) The same syntax yields any percentile — p90 order value, p99 latency:

WITH per_order AS (
  SELECT order_id, sum(quantity * unit_price) AS order_total
  FROM order_items
  GROUP BY order_id
)
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY order_total) AS p50,
       percentile_cont(0.9) WITHIN GROUP (ORDER BY order_total) AS p90
FROM per_order;
 p50 | p90  
-----+------
 798 | 1278
(1 row)

Compare that p50 (the median order, 798) with the Stage 1 project's average order of 659.00 — here the handful of small top-up orders drags the mean well below what a typical order looks like. Averages follow whichever tail is heavier; the gap between the two numbers is itself the finding, and it is why you report both.

🧪 Quick quiz — answer from memory, then check.

  1. Over 1, 2, 3, 4 — what do the two median functions return?
  2. Why report medians alongside averages?
Show the answers
  1. percentile_cont(0.5) returns 2.5 (interpolated); percentile_disc(0.5) returns 2 (an actual value).
  2. Averages follow outliers; medians show the typical case. A big gap between them is information.

Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.

Search the guide