// aggregates reference

SQL MEDIAN function

Returns the middle value of the group, interpolating between the two middle values on even counts.

Catégorie
Aggregates
Returns
numeric
In this category
33 of 52

Syntaxe

MEDIAN(x) | percentile_cont(0.5) WITHIN GROUP (ORDER BY x)

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Different name or syntax no MEDIAN; PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) works as a window function only
PostgreSQL Different name or syntax use percentile_cont(0.5) WITHIN GROUP (ORDER BY x)
MySQL Not built in No built-in equivalent.
SQLite Different name or syntax median() since 3.51.0 when built with SQLITE_ENABLE_PERCENTILE, or the percentile extension
Oracle Oui Supported under this name.

Exemples

Oracle

SELECT dept_id, MEDIAN(salary) FROM employees GROUP BY dept_id;

PostgreSQL

SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY salary) FROM employees;

SQL Server

SELECT DISTINCT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) OVER (PARTITION BY dept_id) FROM employees;

Bon à savoir

  • Even counts interpolate: the result may be a value that exists in no row; PERCENTILE_DISC never does that.
  • SQL Server's PERCENTILE_CONT is window-only, so a per-group median needs OVER (PARTITION BY ...) plus DISTINCT or a subquery.
  • MySQL has neither; the window recipe is averaging the two middle rows found with ROW_NUMBER over the ordered values.
  • NULLs are skipped on every engine.

Questions about MEDIAN

Median vs average?

The median ignores how extreme the tails are; one huge outlier drags the average but barely moves the median.

Why is my median not an actual row value?

Even counts interpolate between the two middle values; use PERCENTILE_DISC(0.5) to get a real value.

What is the median in MySQL?

No built-in: average the two middle values located with ROW_NUMBER or COUNT over an ordered subquery.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.