// window reference

SQL PERCENTILE_CONT vs PERCENTILE_DISC

Both compute a percentile from an ordered set, but CONT interpolates between neighbouring values while DISC snaps to an actual value from the data.

Category
Window
Returns
numeric (CONT) / type of x (DISC)
In this category
12 of 79

Syntax

PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) | PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x)

Engine support

EngineSupportNotes
SQL Server Yes Supported under this name.
PostgreSQL Yes Supported under this name.
MySQL Not built in neither exists; use CUME_DIST or NTILE
SQLite Not built in neither exists; use CUME_DIST or NTILE
Oracle Yes Supported under this name.

Examples

PostgreSQL

SELECT PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY price) AS p25,
       PERCENTILE_DISC(0.25) WITHIN GROUP (ORDER BY price) AS p25_disc
FROM products;

Good to know

  • With an even row count, the median differs: CONT averages the two middle values, DISC returns the lower one. Salaries of 40k and 50k give a 45k median under CONT, 40k under DISC.
  • CONT needs a type it can interpolate: numerics everywhere, plus interval in PostgreSQL and date/timestamp in Oracle. DISC accepts any orderable type, so it is the only option for a median of text values.
  • SQL Server allows both only with OVER (PARTITION BY); PostgreSQL allows them only as aggregates (no OVER); Oracle allows either form.

Questions about PERCENTILE_CONT vs PERCENTILE_DISC

Which one should I use for a median?

CONT when the median of an even count should average the middle two (financial convention); DISC when the answer must be a value that actually exists, or when the column is not numeric.

Why does PERCENTILE_CONT error on a date column?

Interpolating between two dates needs arithmetic on the type. SQL Server accepts only numerics, PostgreSQL only double precision and interval (no function matches a date argument); Oracle does interpolate DATE and TIMESTAMP values. DISC works on dates everywhere it exists.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, Oracle.

// fewer lookups

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.