MEDIAN

MEDIAN is a function in SQL that returns the middle value in a sorted set of values. If the total number of values in the dataset is even, the result of the MEDIAN function is the average of the two middle values. This function is used to find the central tendency of a series of values.

Example

SELECT MEDIAN(salary) OVER () AS median_salary
FROM employees;

Output

MEDIAN_SALARY
--------------
5000.0

Explanation

This query is computing the median of all the values present in the salary column from the employees table. The median is the middle value in an ordered list of numbers. Here, the median salary is 5000.0.

Example

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

Output

median
--------
52000
(1 row)

Explanation

The function percentile_cont(0.5) calculates the median of the ‘salary’ column. The WITHIN GROUP (ORDER BY salary) portion sorts the salaries in ascending order. The calculated median of ‘salary’ is then returned, which in this example is 52000.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.