// aggregates reference

SQL WITHIN GROUP clause

The clause that hands an aggregate a sorted input, powering percentiles, modes and hypothetical ranks.

カテゴリ
Aggregates
Returns
depends on the aggregate
In this category
47 of 52

構文

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

エンジンサポート

エンジンSupportメモ
SQL Server Different name or syntax PERCENTILE_CONT and PERCENTILE_DISC need OVER; STRING_AGG and APPROX_PERCENTILE_CONT/DISC (2022+) take WITHIN GROUP as plain aggregates
PostgreSQL はい Supported under this name.
MySQL Not built in no WITHIN GROUP; emulate with window functions
SQLite Not built in No built-in equivalent.
Oracle はい Supported under this name.

例

PostgreSQL

SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY ms) FROM requests;

Oracle

SELECT PERCENTILE_DISC(0.9) WITHIN GROUP (ORDER BY ms) FROM requests;

PostgreSQL

SELECT mode() WITHIN GROUP (ORDER BY status) FROM orders;

知っておくと便利なこと

  • The syntax is function(args) WITHIN GROUP (ORDER BY col): the ordering lives outside the parentheses, unlike every normal aggregate.
  • Percentiles and mode() take exactly one ORDER BY expression; the function's own arguments carry parameters like the fraction. LISTAGG and STRING_AGG accept a multi-column ORDER BY.
  • Hypothetical-set forms (RANK, DENSE_RANK, PERCENT_RANK, CUME_DIST with arguments) also use WITHIN GROUP.
  • MySQL has no ordered-set aggregates. SQLite 3.51 builds with SQLITE_ENABLE_PERCENTILE offer median(x) and percentile_cont(x, p) as plain functions, without WITHIN GROUP.

Questions about WITHIN GROUP

Why does WITHIN GROUP exist?

Some aggregates need their input sorted first; the clause says which column to sort, separate from the function's own arguments.

Which engines support it?

PostgreSQL and Oracle fully. SQL Server for STRING_AGG and the APPROX_PERCENTILE functions as plain aggregates, and for PERCENTILE_CONT/DISC only with OVER. MySQL and SQLite not at all.

Can I put multiple columns in the ORDER BY?

Not for percentiles or mode(), which need exactly one sort expression. String aggregates such as LISTAGG and STRING_AGG accept several, and hypothetical-set functions take one per argument.

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.