r/mysql • u/pancakepizza2 • Aug 11 '26
question Why doesn't MySQL have a median function?
I was a bit surprised that MySQL Workbench has no built-in median function similar to AVG, SUM etc. The current way to get the median is to write a fairly lengthy query (compared to simply using the aggragate functions), is there a particular reason why it hasn't been implemented?
11
Upvotes
5
u/Aggressive_Ad_5454 Aug 11 '26
Workbench is a client program, an obsolete one at that.
PERCENTILE_CONT( 0.5 ) is a window function which is useful to get the median. In MariaDb. In MySql it’s PERCENT_RANK().
3
u/Jonas_Ermert Aug 12 '26
There’s no technical reason MySQL couldn’t have `MEDIAN()`. Historically, median is more expensive than `AVG()` or `SUM()` because it requires ordering the values and finding the middle. Still, with modern MySQL supporting window functions, a built-in `MEDIAN()` or `PERCENTILE_CONT()` would be a very reasonable addition.
22
u/anvildoc Aug 11 '26
Median is not a scalar function — it’s an ordered window function — so you need to take the whole dataset and sort it and then you can return the median. So it is waaay more heavy than regular aggregations or simpler window functions
7
u/johannes1234 Aug 11 '26
The median doesn't work like the accumulator pattern, where you process a value at a time, by scrolling through the dataset, but is more involved as you have to first sort the data. Thus it can't be done like the aggregations. (When calculating average you simply take the values in any order, sum them up and count number of values and then divide (if your number space is big enough for the sum, but there are easy solutions for that as well))
Calculating Median thus involves more choices, which depend on data, the more you know your data the more you can optimize it and there is no single implementation doing it good in enough cases. Thus it would promise a solution, which will lead to trouble at some point. The "manual" solutions make the limitations more obvious.
2
u/roXplosion Aug 12 '26
Check out this discussion:
https://www.geeksforgeeks.org/sql/calculate-median-in-mysql/
Tip: make sure there is an index on the
ORDER BYfield.2
u/gotnotendies Aug 16 '26
You can try submitting a PR for it, but the most frequent reason for “why does X not exist in Y open source product?” is because no one bothered to add it in.
Some devs/DBAs also get protective of their workarounds for limitations and defend it itself.
Doesn’t help that Oracle owns MySQL and has never wanted to support its business usage, while MariaDB was forked by a group that wants to make it successful and popular, and most importantly - is passionate about it.
[MySQL cofounder forked into MariaDB when Oracle bought MySQL]