// window reference

SQL RANK WITHIN GROUP

The inverse-distribution form of RANK: it returns the rank the given value would have if it were inserted into the ordered set.

Catégorie
Fenêtre
Returns
bigint / double precision
In this category
13 of 79

Syntaxe

RANK(42) WITHIN GROUP (ORDER BY score) | PERCENT_RANK(42) WITHIN GROUP (ORDER BY score)

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Not built in no hypothetical-set aggregates; count the rows that sort before the value
PostgreSQL Oui RANK, DENSE_RANK, PERCENT_RANK and CUME_DIST all take WITHIN GROUP
MySQL Not built in no hypothetical-set aggregates; count the rows that sort before the value
SQLite Not built in no hypothetical-set aggregates; count the rows that sort before the value
Oracle Oui RANK, DENSE_RANK, PERCENT_RANK and CUME_DIST all take WITHIN GROUP

Exemples

PostgreSQL

-- the rank a score of 85 would get
SELECT RANK(85) WITHIN GROUP (ORDER BY score DESC) AS would_be
FROM scores;

Any engine

-- portable emulation: ties share the lower rank
SELECT COUNT(*) + 1 AS would_be
FROM scores WHERE score > 85;

Bon à savoir

  • The argument count must match the ORDER BY list: RANK(10, 'A') WITHIN GROUP (ORDER BY x, y) is valid, and a mismatched count is rejected before the query runs.
  • This is an aggregate, not a window function: no OVER clause. It answers 'where does this threshold land?' in one pass instead of ranking every row and searching.
  • SQL Server, MySQL and SQLite emulate it by counting: RANK(v) is 1 + the rows that sort strictly before v, DENSE_RANK(v) is 1 + the distinct values before v, and PERCENT_RANK(v) is the rows before v divided by the total row count.

Questions about RANK WITHIN GROUP

When would I use RANK WITHIN GROUP instead of RANK()?

When you have a threshold value, not rows to rank: 'which percentile is 85 points?' or 'what rank would this candidate's salary get?' without materializing a ranking of the whole table.

Why is my emulated rank off by one?

Rows equal to the value must not be counted: RANK(85) is 1 + COUNT of scores strictly better than 85, so use > for a DESC ordering, not >=. Counting the ties too gives the rank after them.

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.