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.
Related on SQLly
- Top-N with ties per group Snippet
- Rank rows within a category Snippet
- Mix window functions with GROUP BY Snippet
- SQL window function interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.