// window reference

SQL RANK function

Ranks rows within a partition, giving tied rows the same rank and skipping the subsequent numbers: 1, 2, 2, 4. That gap behaviour is the whole difference from DENSE_RANK.

카테고리
창
Returns
bigint
In this category
2 of 79

구문

RANK() OVER (PARTITION BY g ORDER BY x)

엔진 지원

엔진Support메모
SQL Server 예 Supported under this name.
PostgreSQL 예 Supported under this name.
MySQL 예 MySQL 8.0+
SQLite 예 SQLite 3.25+
Oracle 예 Supported under this name.

예시

Any engine

-- RANK is a reserved word in MySQL 8, so the alias is not rank
SELECT name, points,
       RANK() OVER (ORDER BY points DESC) AS position
FROM players;

Any engine

SELECT department, salary,
       RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank
FROM employees;

알아 두면 좋은 정보

  • Ties share a rank and the next rank jumps: scores 10, 10, 9 rank 1, 1, 3. DENSE_RANK gives 1, 1, 2; ROW_NUMBER gives 1, 2, 3.
  • The ORDER BY inside OVER decides what counts as a tie. Leave it out and every row is a tie, so PostgreSQL, MySQL and SQLite rank every row 1; SQL Server and Oracle (ORA-30485) refuse RANK without ORDER BY.
  • RANK is also available in a plain aggregate form (RANK(x) WITHIN GROUP (ORDER BY y)) on PostgreSQL and Oracle: the rank a value would get inside the group.

Questions about RANK

What is the difference between RANK and DENSE_RANK?

Gaps after ties. Scores 10, 10, 9 rank as 1, 1, 3 with RANK and 1, 1, 2 with DENSE_RANK. Both differ from ROW_NUMBER, which never ties.

Can RANK be used for pagination?

Use ROW_NUMBER for pagination. With RANK, tied rows share a number and the next numbers are skipped, so WHERE rank BETWEEN 11 AND 20 can return more or fewer than ten rows. RANK suits leaderboards where sharing a position is correct.

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.