Function to Calculate Median in SQL Server
How can you calculate the median value in SQL Server when there is no built-in MEDIAN function?
What SQL techniques or window functions can be used to compute the median efficiently from a dataset?
SQL Server doesn’t provide a built-in MEDIAN() function like some other databases do. However, you can calculate the median using window functions such as ROW_NUMBER() or PERCENTILE_CONT(). The method you choose depends on whether you want a precise median for all rows or based on groups.
Recommended Method: PERCENTILE_CONT()
This function calculates the median statistically and works well for both even and odd row counts:
SELECT
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ValueColumn)
OVER () AS MedianValue
FROM TableName;- 0.5 represents the 50th percentile (median)
- The OVER() clause applies it to the entire dataset
If you need median per group (e.g., category):
SELECT
Category,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ValueColumn)
OVER (PARTITION BY Category) AS MedianValue
FROM TableName; Alternative Method (Manual Calculation via Ranking)
Useful for older SQL Server versions:
WITH OrderedData AS (
SELECT ValueColumn,
ROW_NUMBER() OVER (ORDER BY ValueColumn) AS RowNum,
COUNT(*) OVER () AS TotalRows
FROM TableName
)
SELECT AVG(ValueColumn) AS MedianValue
FROM OrderedData
WHERE RowNum IN ((TotalRows + 1) / 2, (TotalRows + 2) / 2);Works whether the row count is odd or even
In summary, while SQL Server doesn’t directly support a median function, PERCENTILE_CONT() offers an efficient and modern solution — and ranking methods provide a solid backup for compatibility.