PERCENTILE_CONT Function
The percentile function in SQL calculates the value at a given percentile (for example, 25th, 50th/median, or 90th) across a set of rows, effectively telling you “what value cuts off the bottom X% of the data.”
Sample Syntax
| id | name | salary |
|----|-------|--------|
| 1 | Alice | 5000 |
| 2 | Bob | 6000 |
| 3 | Carol | 7000 |
| 4 | Dave | 8000 |
| 5 | Eve | 9000 |
SELECT
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary
FROM employees;
- Given a column of numbers and a percentage like 0.25 (25th percentile) or 0.9 (90th percentile), the function computes the value at the given position in the sorted data (e.g, 50th percentile value)
- Without the
ORDER BY, the database will not know which order to arrange the salaries in, so it cannot decide which value corresponds to the percentile. - This returns the median salary (50th percentile) of all employees.