The DENSE_RANK() function assigns ranks to rows within a partition based on a specified order. Crucially, it assigns consecutive ranks without gaps, unlike the RANK() function. This is useful for scenarios where you need a continuous ranking, such as in league tables or performance evaluations.
The `DENSE_RANK()` function in SQL is a window function that assigns a rank to each row within a partition based on the values of one or more columns. It's similar to the `RANK()` function, but it differs in how it handles ties. When multiple rows have the same value in the ranking column, `RANK()` assigns the same rank and skips the next rank. `DENSE_RANK()`, on the other hand, assigns consecutive ranks without gaps. This means that if two rows have the same rank, the next rank is immediately assigned to the following row, maintaining a continuous sequence. This is often preferred for situations where a gap in ranking would be misleading, such as in a leaderboard where you want to see a clear progression of ranks. For example, if three students have the same score, `RANK()` might assign ranks 1, 1, 1, and then 4 to the next student, whereas `DENSE_RANK()` would assign ranks 1, 1, 1, and then 2 to the next student. This makes `DENSE_RANK()` more suitable for situations where a continuous ranking is desired. It's important to understand that `DENSE_RANK()` is a window function, meaning it operates on a set of rows (a partition) and returns a value for each row within that partition. The function is often used in conjunction with other window functions to perform more complex analyses on data.
Understanding `DENSE_RANK()` is crucial for creating accurate and meaningful rankings in various applications. It's essential for tasks like generating league tables, performance evaluations, and data analysis where a continuous ranking without gaps is needed to avoid misinterpretations.
Choose DENSE_RANK()
whenever you need consecutive, gap-free ranking—such as leaderboards, sales tiers, or exam score tables—where a skipped rank like 1, 1, 1, 4
(produced by RANK()
) could be confusing. DENSE_RANK()
returns 1, 1, 1, 2
, giving readers an intuitive, continuous sequence.
Because DENSE_RANK()
is a window function, the PARTITION BY
clause restarts the ranking for each group defined in the OVER
clause. Each partition begins at rank 1, so rows are compared only to others in the same partition—perfect for ranking students within each class or products within each category.
Galaxy’s context-aware AI copilot autocompletes window-function syntax, recommends the best ORDER BY
and PARTITION BY
columns, and can even refactor an existing RANK()
query into DENSE_RANK()
. This accelerates SQL development and minimizes errors compared to traditional editors.