percentiles, medians and string_agg
aggregates that care about order: WITHIN GROUP, percentile_cont vs percentile_disc, and ordered string_agg.
- address
- everything.analytics.ordered_set_aggregates
- part
- part 4, windows, grouping and recursion
- chapter
- chapter 3 of 11
- reading time
- 7 min
most aggregates don't care what order rows arrive in: a sum is a sum. a few do. an ordered-set aggregate takes its order in WITHIN GROUP (ORDER BY ...): percentile_cont(0.5) WITHIN GROUP (ORDER BY salary) is the median.
percentile_cont interpolates between the two middle values. percentile_disc returns an actual value from the data. and string_agg / array_agg take an ORDER BY inside their parentheses, or their order is anybody's guess.
the picture
you know how the "average salary" in a company with one CEO is a number nobody actually earns? the median is the middle person's salary instead, and a median depends on the order of the values, which a plain aggregate never asks for. so SQL needed a way to hand an aggregate an order: WITHIN GROUP.
think of lining people up by height and asking for the one in the middle. with an odd number of people there's a middle person. with an even number there isn't, and you have two choices: report a height halfway between the two middle people (cont, continuous), or point at one of them (disc, discrete).
cont: position 3.5 in 0 to 7 falls between Tomás Ortega (85,000) and Lena Fischer (87,000), so it interpolates: 86,000.disc: the first value with at least 50% of the rows at or below it: Tomás Ortega, 85,000 (4 of 8).
WITHIN GROUP
the fraction goes in the function's parentheses, the order in WITHIN GROUP:
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY salary) AS median_cont,
percentile_disc(0.5) WITHIN GROUP (ORDER BY salary) AS median_disc,
round(avg(salary)) AS avg
FROM instructors;| median_contfloat8 | median_discnumeric | avgnumeric |
|---|---|---|
| 86000 | 85000.00 | 85625 |
the two answers, made the long way:
- percentile_cont(f) puts the sorted values at positions 0 to n−1 and goes to position f × (n − 1). with 8 values, the median is position 3.5: halfway between the 4th and 5th salary, 85,000 and 87,000. the result is a
double precision, and the column has to be numeric (or an interval). - percentile_disc(f) returns the first value whose position in the sorted list (counting from 1, out of n) is at least f of the way. 4 of 8 is exactly half, so it's the 4th, 85,000. it works on anything sortable, text included.
pass an array of fractions and you get an array back, one answer each, in one pass: percentile_cont(ARRAY[0.25, 0.5, 0.75]) gives the quartiles. (that's how the figure was captured.)
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY v)
FROM unnest(ARRAY[10, 1, 3, 2]) AS v;SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY v) AS cont,
percentile_disc(0.5) WITHIN GROUP (ORDER BY v) AS disc,
avg(v) AS avg
FROM unnest(ARRAY[10, 1, 3, 2]) AS v;| contfloat8 | discint4 | avgnumeric |
|---|---|---|
| 2.5 | 2 | 4.0000000000000000 |
when the average lies
an average gets dragged by a few big values; a median doesn't move. the shop's product prices, in the categories where the two disagree most:
SELECT category,
round(avg(price), 2) AS avg,
percentile_cont(0.5) WITHIN GROUP (ORDER BY price)::numeric(10,2) AS median,
count(*) AS products
FROM products
WHERE category IN ('pets', 'books')
GROUP BY category
ORDER BY category;| categorytext | avgnumeric | mediannumeric | productsint8 |
|---|---|---|---|
| books | 92.15 | 76.31 | 12 |
| pets | 115.96 | 148.11 | 17 |
ordered-set aggregates group like any other aggregate, so a median per category is just GROUP BY category. the ::numeric(10,2) is there because percentile_cont answers in double precision.
on text, and the most common value
percentile_disc only ever returns a value from the data, so it works on any type with an order. the median grade, and mode(), the most frequent value:
SELECT percentile_disc(0.5) WITHIN GROUP (ORDER BY grade) AS median_grade,
mode() WITHIN GROUP (ORDER BY grade) AS most_common,
count(grade) AS graded
FROM enrollments;| median_gradechar | most_commonchar | gradedint8 |
|---|---|---|
| B | B | 101 |
B both times, from 101 graded enrollments. (mode's ORDER BY only matters for ties: with two equally common values, it returns the first in that order.) percentile_cont can't interpolate between two letters. there isn't even a version of it that takes text:
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY grade) FROM enrollments;string_agg and array_agg
these are ordinary aggregates, but their result shows the order the rows arrived in. without an ORDER BY, that order is whatever the plan produced, and it can change. so the order goes inside the parentheses, right after the argument:
- 1SELECT dept, string_agg(name, ', ' ORDER BY name) AS instructors
- 2FROM instructors
- 3GROUP BY dept
- 4ORDER BY dept;
| depttext | instructorstext |
|---|---|
| CS | Hannah Okoye, Lena Fischer, Marco Rossi, Sofia … |
| HIST | Oliver Grant |
| MATH | Tomás Ortega, Yuki Tanaka |
| PHYS | Amara Diallo |
ORDER BY name inside the aggregate: each department's instructors, alphabetically.
with DISTINCT, the ORDER BY may only use the expression being aggregated (anything else couldn't be ordered once the duplicates are gone):
SELECT dept, string_agg(DISTINCT credits::text, ', ' ORDER BY credits::text) AS credit_values
FROM courses
GROUP BY dept
ORDER BY dept;| depttext | credit_valuestext |
|---|---|
| CS | 4 |
| GEN | 6 |
| HIST | 3 |
| MATH | 3, 4 |
| PHYS | 4 |
this page's checker flags any string_agg, array_agg or json_agg without an inner ORDER BY, for the same reason it flags a multi-row result without one (ORDER BY).
what rank would I have?
the last family is hypothetical-set aggregates: where would this value land if it were in the group? same WITHIN GROUP, with the value in the parentheses:
SELECT rank(88000) WITHIN GROUP (ORDER BY salary DESC) AS rank_of_88k,
round(percent_rank(88000) WITHIN GROUP (ORDER BY salary DESC)::numeric, 3) AS percent_rank
FROM instructors;| rank_of_88kint8 | percent_ranknumeric |
|---|---|
| 4 | 0.375 |
a new hire on 88,000 would rank 4th of the 9 (three people earn more). they're the aggregate cousins of the window functions in row_number, rank and dense_rank.
keylines
- WITHIN GROUP (ORDER BY ...) hands an aggregate the order it needs.
- percentile_cont interpolates (numbers only). percentile_disc returns a real value (any type).
- the median is percentile_cont(0.5). an array of fractions gets an array of answers.
- string_agg and array_agg take ORDER BY inside the parentheses, or their order isn't promised.
- ordered-set aggregates can't take OVER: GROUP BY and join back.