SQL DENSE_RANK function
Ranks rows within a partition like RANK, but never skips numbers after a tie: 1, 2, 2, 3. It also numbers the distinct values of a column without a GROUP BY.
- 类别
- 窗口
- Returns
bigint- In this category
- 3 of 79
语法
DENSE_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
SELECT name, points,
DENSE_RANK() OVER (ORDER BY points DESC) AS position
FROM players;
Any engine
SELECT category,
DENSE_RANK() OVER (ORDER BY category) AS category_no
FROM products;
值得了解
- Because the numbers never skip, DENSE_RANK() OVER (ORDER BY category) gives each distinct category its own number, 1, 2, 3..., and MAX of it is the number of distinct categories.
- On MySQL before 8.0 and SQLite before 3.25 there is no DENSE_RANK; user variables or a DISTINCT + COUNT subquery emulate it.
- Like all window functions, it cannot be used in WHERE. Compute it in a CTE and filter outside: WHERE dr <= 3 keeps every row in the top three distinct scores, ties included.
Questions about DENSE_RANK
When should I use DENSE_RANK instead of RANK?
When the gaps hurt: leaderboards that publish 1, 2, 2, 3 rather than 1, 2, 2, 4, or numbering distinct values without a GROUP BY.
Does DENSE_RANK work on MySQL 5.7?
No. Window functions arrived in MySQL 8.0. On 5.7, a correlated subquery does it: (SELECT COUNT(DISTINCT p2.points) FROM players p2 WHERE p2.points >= p.points).
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Dedupe with window functions Snippet
- Second-highest value Snippet
- Top-N with ties per group Snippet
- Rank rows within a category 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.