SQL APPROX_PERCENTILE_CONT function
Exact percentiles sort the whole group. The approximate versions build a small sketch instead, so a p95 over a billion rows needs far less memory.
- Categoría
- Aggregates
- Returns
float- In this category
- 51 of 52
Sintaxis
APPROX_PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY expr)
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | APPROX_PERCENTILE_CONT and APPROX_PERCENTILE_DISC, 2022+ |
| PostgreSQL | Not built in | no; exact percentile_cont, or an extension such as tdigest |
| MySQL | Not built in | no percentile aggregates |
| SQLite | Not built in | no percentile aggregates |
| Oracle | Different name or syntax | APPROX_PERCENTILE(p) WITHIN GROUP (ORDER BY x) from 12.2; add DETERMINISTIC for repeatable results |
Ejemplos
SQL Server
SELECT APPROX_PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) AS median_cont,
APPROX_PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x) AS median_disc
FROM (VALUES (1), (2), (3), (4)) AS t(x); -- 2.5, 2
SQL Server
SELECT g, APPROX_PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY x) AS p95
FROM (VALUES ('a', 1), ('a', 9), ('b', 5)) AS t(g, x)
GROUP BY g;
Oracle
SELECT APPROX_PERCENTILE(0.5 DETERMINISTIC) WITHIN GROUP (ORDER BY x) AS median FROM (SELECT LEVEL AS x FROM dual CONNECT BY LEVEL <= 4); -- 2
Conviene saberlo
- SQL Server builds a KLL sketch, a randomized algorithm: Microsoft documents a rank-based error of up to 1.33% at 99% confidence, and results can differ between runs.
- It is a plain aggregate with GROUP BY. SQL Server's exact PERCENTILE_CONT needs an OVER clause instead.
- On small groups the estimate is usually exact, so tests on toy data will not show the approximation.
Questions about APPROX_PERCENTILE_CONT
When should I use the approximate version?
For dashboards and monitoring over large tables, where a 1% rank error is acceptable. Use PERCENTILE_CONT when the number must match a report exactly.
What does PostgreSQL offer?
Exact percentile_cont and percentile_disc as ordered-set aggregates with GROUP BY. Approximate percentiles need an extension.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, 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.