// aggregates reference

SQL hypothetical-set aggregates

Ranks a hypothetical row as if it were inserted, without inserting it.

Categoría
Aggregates
Returns
integer or numeric
In this category
48 of 52

Sintaxis

RANK(v) WITHIN GROUP (ORDER BY col) | CUME_DIST(v) WITHIN GROUP (ORDER BY col)

Soporte del motor

MotorSupportNotas
SQL Server Not built in same UNION ALL emulation
PostgreSQL Sí Supported under this name.
MySQL Not built in emulate with UNION ALL of the hypothetical value plus a window function
SQLite Not built in same UNION ALL emulation
Oracle Sí Supported under this name.

Ejemplos

PostgreSQL

SELECT rank(1500) WITHIN GROUP (ORDER BY salary) FROM employees;

Oracle

SELECT RANK(1500) WITHIN GROUP (ORDER BY salary) FROM employees;

Conviene saberlo

  • The hypothetical row's values are the function's arguments; the ORDER BY list must match in count and sortability.
  • RANK(v) is 1 plus the number of existing values that sort strictly before v; existing values equal to v tie with it rather than push it down.
  • The window versions of RANK and friends rank rows that exist; the WITHIN GROUP versions rank a value that does not.
  • Emulation recipe elsewhere: SELECT ... UNION ALL the value, then window-rank and filter out the injected row.

Questions about RANK

What is a hypothetical-set aggregate for?

Placement questions: 'what rank would a salary of 1500 get?' without writing the row first.

How is it different from window RANK?

Window RANK ranks existing rows after PARTITION BY; the hypothetical form ranks an argument value against the data.

Which engines support it?

PostgreSQL and Oracle; MySQL, SQL Server and SQLite need the UNION ALL plus window-function emulation.

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

// 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.