skip to content

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).

fraction =
0.50
72k79k83k85k87k90k91k98kcont 86,000
percentile_contpercentile_disc (a real row)

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).

real output, postgres 18.6 (PGlite 0.5.12) · ordered-set-aggregates
the school's eight instructors by salary. slide the fraction. percentile_cont slides smoothly between the values; percentile_disc jumps from one real salary to the next. at 0.5 (the median), cont says 86,000, which nobody earns, and disc says 85,000, which Tomás Ortega does.

WITHIN GROUP

the fraction goes in the function's parentheses, the order in WITHIN GROUP:

sqldb=school
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;
output, from postgres 18.6
SELECT 1
median_contfloat8median_discnumericavgnumeric
8600085000.0085625
(1 row)

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.)

predict the output
sql
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY v)
FROM unnest(ARRAY[10, 1, 3, 2]) AS v;
sqlempty db
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;
output, from postgres 18.6
SELECT 1
contfloat8discint4avgnumeric
2.524.0000000000000000
(1 row)

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:

pets: avg115.96
pets: median148.11
books: avg92.15
books: median76.31
outdoor: avg103.66
outdoor: median95.54
bath: avg105.21
bath: median112.21
avg vs median price per category, the four categories where they're furthest apart. pets' median is 148.11 but its average is 115.96: a handful of cheap products drag the average down. books goes the other way.
sqldb=shop
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;
output, from postgres 18.6
SELECT 2
categorytextavgnumericmediannumericproductsint8
books92.1576.3112
pets115.96148.1117
(2 rows)

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:

sqldb=school
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;
output, from postgres 18.6
SELECT 1
median_gradecharmost_commonchargradedint8
BB101
(1 row)

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:

sqldb=school
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY grade) FROM enrollments;
output, from postgres 18.6
ERROR 42883: function percentile_cont(numeric, character) does not exist
1 │ SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY grade) FROM enrollments;
at line 1, column 8
HINT: No function matches the given name and argument types. You might need to add explicit type casts.

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:

inside =
query.sql
  1. 1SELECT dept, string_agg(name, ', ' ORDER BY name) AS instructors
  2. 2FROM instructors
  3. 3GROUP BY dept
  4. 4ORDER BY dept;
the result for ORDER BY name
depttextinstructorstext
CSHannah Okoye, Lena Fischer, Marco Rossi, Sofia …
HISTOliver Grant
MATHTomás Ortega, Yuki Tanaka
PHYSAmara Diallo
(4 rows)

ORDER BY name inside the aggregate: each department's instructors, alphabetically.

real output, postgres 18.6 (PGlite 0.5.12) · ordered-set-aggregates
switch the inner ORDER BY. same groups, same people, a different order inside each list: in CS, Marco Rossi moves ahead of Lena Fischer. the query's own ORDER BY dept only orders the rows.

with DISTINCT, the ORDER BY may only use the expression being aggregated (anything else couldn't be ordered once the duplicates are gone):

sqldb=school
SELECT dept, string_agg(DISTINCT credits::text, ', ' ORDER BY credits::text) AS credit_values
FROM courses
GROUP BY dept
ORDER BY dept;
output, from postgres 18.6
SELECT 5
depttextcredit_valuestext
CS4
GEN6
HIST3
MATH3, 4
PHYS4
(5 rows)

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:

sqldb=school
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;
output, from postgres 18.6
SELECT 1
rank_of_88kint8percent_ranknumeric
40.375
(1 row)

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.