JournalSQLAggregation2 min

3 Ways for Calculating Median in PostgreSQL

One quick note that a median might be a more appropriate measure of center for this data, but finding the median happens to be a pretty difficult thing to get using SQL alone — so difficult that finding a median is occasionally asked as an interview question.

  • median
  • PERCENTILE_CONT
  • NTILE
  • PostgreSQL

As mentioned in Lesson 6.10 Video: AVG:

MEDIAN - Expert Tip

One quick note that a median might be a more appropriate measure of center for this data, but finding the median happens to be a pretty difficult thing to get using SQL alone — so difficult that finding a median is occasionally asked as an interview question.

Median (not AVG) is not directly supported in PostgreSQL. But fortunately, we can calculate it in multiple ways.

WARNING: This topic is advanced, If you want to just solve the quiz of Lesson 6 check that topic.

Analytic way

These implementations is quite slow. On tables of ~500K elements orafce implementation is ~400 times faster. Check Further resources section for info about orafce package.

First Method

Based on PG Wiki

CREATE OR REPLACE FUNCTION _final_median(NUMERIC[])
   RETURNS NUMERIC AS
$$
   SELECT AVG(val)
   FROM (
     SELECT val
     FROM unnest($1) val
     ORDER BY 1
     LIMIT  2 - MOD(array_upper($1, 1), 2)
     OFFSET CEIL(array_upper($1, 1) / 2.0) - 1
   ) sub;
$$
LANGUAGE 'sql' IMMUTABLE;
 
CREATE AGGREGATE median(NUMERIC) (
  SFUNC=array_append,
  STYPE=NUMERIC[],
  FINALFUNC=_final_median,
  INITCOND='{}'
);

Usage

SELECT median(num_value) AS median_value FROM t;

Second method

Based on Pavel Stehule's blog post

SELECT avg(a)::float
FROM (SELECT a, row_number() OVER (ORDER BY a asc) AS hi,
                count(*) OVER () + 1 - row_number() OVER (ORDER BY a) AS lo
          FROM milrows) qs
WHERE hi IN (lo-1,lo,lo+1);

Third method

Based on Pavel Stehule's blog post

select avg(a)
   from ( select a, row_number() over (order by a),count(*) over () from milrows ) s
  where row_number between floor((count::float8-1)/2+1) and ceil((count::float8-1)/2+1);

Fourth method

Based on Pavel Stehule's blog post

select avg(a)
   from ( select a, row_number() over (order by a),(select count(*) from milrows) as count from milrows ) s
  where row_number between floor((count::float8-1)/2+1) and ceil((count::float8-1)/2+1);

Array-based way

Based on Pavel Stehule's blog post

These methods are fast, but limit for this methods is size of operation memory. For very very large tables could to take all application memory.

SELECT CASE WHEN c % 2 = 0 AND c > 1 THEN (a[1]+a[2])/2 ELSE a[1] END
FROM
(
 SELECT ARRAY(SELECT my_col FROM my_table ORDER BY my_cal OFFSET (c-1)/2 LIMIT 2) AS a, c
   FROM (SELECT count(*) AS c FROM my_table where my_col is not null) AS count
 OFFSET 0
)
AS midrows;

ntile function

Based on Carbon Five blog post

From Official documentation about window functions:

ntile(num_buckets integer) integer ranging from 1 to the argument value, dividing the partition as equally as possible

SELECT
  MAX(column) as "Median of Column"
FROM
  (
    SELECT
      column,
      ntile(2) OVER (ORDER BY column) AS bucket
    FROM
      table
  ) as t
WHERE bucket = 1
GROUP BY bucket;

References:

Further resources