SQL PERCENTILE_CONT function
Returns the value at a given fraction of the ordered group, interpolating between the two nearest values. PERCENTILE_CONT(0.5) is the median.
- Returns
numeric- In this category
- 10 of 52
语法
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) -- aggregate form
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | 是 | window form only: it always needs an OVER clause |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | Not built in | no PERCENTILE_CONT; emulate with window functions |
| SQLite | Different name or syntax | percentile_cont(x, 0.5) and median(x) in 3.47+ builds with the percentile extension enabled, as in the sqlite3 shell |
| Oracle | 是 | aggregate or analytic; MEDIAN(x) as a shortcut |
示例
PostgreSQL
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY response_ms) AS median FROM pings;
SQL Server
SELECT DISTINCT
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY response_ms)
OVER () AS median
FROM pings;
Oracle
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY response_ms) AS median FROM pings;
值得了解
- SQL Server requires the window form: PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) OVER (PARTITION BY g). It returns the value on every row, so add DISTINCT or a GROUP BY around it to get one row per group.
- PostgreSQL only has the aggregate form: PERCENTILE_CONT cannot be used as a window function there, so compute one group per query or wrap it in a grouped subquery.
- 0.5 gives the median. For p95 use 0.95; the result interpolates between the two nearest rows when no row lands exactly on the fraction.
Questions about PERCENTILE_CONT
How do I compute a median in SQL?
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) on PostgreSQL and Oracle (Oracle also has MEDIAN(x)), the same expression with an OVER () clause on SQL Server. On MySQL, number the rows with ROW_NUMBER and COUNT and average the middle one or two. SQLite builds with the percentile extension have median(x).
What is the difference between PERCENTILE_CONT and PERCENTILE_DISC?
CONT interpolates between neighbouring values and can return a value that exists in no row; DISC returns an actual row value, skipping interpolation.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Median per group Snippet
- Percentile buckets Snippet
- Find outliers with percentiles Snippet
- SQL aggregation & HAVING interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, SQLite, Oracle.
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.