Sub topic 6
Ranking rows with RANK and DENSE_RANK
This chapter assumes you can read an OVER (PARTITION BY ... ORDER BY ...) clause and have used ROW_NUMBER. It covers how RANK and DENSE_RANK treat tied values, how to pick between them, and the mistakes that cause wrong results.
Why ranking differs from numbering
ROW_NUMBER always gives every row a different number, even when two rows have equal sort values. That is the wrong behaviour when two employees earn the same salary and should share a position. RANK and DENSE_RANK solve this by giving rows with equal sort values the same rank. They differ in what happens to the number after a tie.
RANKleaves a gap. If two rows share rank 2, the next rank is 4.DENSE_RANKleaves no gap. If two rows share rank 2, the next rank is 3.
The syntax is the same as for ROW_NUMBER:
RANK() OVER ([PARTITION BY expr, ...] ORDER BY expr [ASC|DESC] [NULLS FIRST|LAST], ...)
DENSE_RANK() OVER ([PARTITION BY expr, ...] ORDER BY expr [ASC|DESC] [NULLS FIRST|LAST], ...)The ORDER BY inside OVER is required. Without it, Oracle has no way to decide which rows tie, and the statement fails. These functions also do not accept a windowing clause such as ROWS BETWEEN. The rank always depends on the whole partition.
The three functions side by side
The query below carries its own data in a WITH clause, so you can run it in any Oracle 11gR2 or later session without creating a table.
WITH employees (employee_id, department_id, salary) AS (
SELECT 101, 10, 9000 FROM dual UNION ALL
SELECT 102, 10, 8000 FROM dual UNION ALL
SELECT 103, 10, 8000 FROM dual UNION ALL
SELECT 104, 10, 7000 FROM dual UNION ALL
SELECT 201, 20, 6000 FROM dual UNION ALL
SELECT 202, 20, 6000 FROM dual UNION ALL
SELECT 203, 20, 5000 FROM dual
)
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS drnk
FROM employees
ORDER BY department_id, salary DESC, employee_id;The result is:
| EMPLOYEE_ID | DEPARTMENT_ID | SALARY | RN | RNK | DRNK |
|---|---|---|---|---|---|
| 101 | 10 | 9000 | 1 | 1 | 1 |
| 102 | 10 | 8000 | 2 | 2 | 2 |
| 103 | 10 | 8000 | 3 | 2 | 2 |
| 104 | 10 | 7000 | 4 | 4 | 3 |
| 201 | 20 | 6000 | 1 | 1 | 1 |
| 202 | 20 | 6000 | 2 | 1 | 1 |
| 203 | 20 | 5000 | 3 | 3 | 2 |
Look at employee 104. RANK reports 4 because three rows are ahead of this one, so the rank is the position the row would have if ties were broken arbitrarily. DENSE_RANK reports 3 because only two distinct salary values are ahead of it.
Which of rn to give employees 102 and 103 is arbitrary here. The outer ORDER BY employee_id only controls display order. It does not change which row ROW_NUMBER numbered first. RANK and DENSE_RANK do not have this problem, because tied rows always get identical values.
What the numbers mean
The two functions have precise definitions, which are useful for checking results.
| Function | Value for a row |
|---|---|
| `RANK` | 1 plus the number of rows in the partition that sort strictly before this row |
| `DENSE_RANK` | 1 plus the number of distinct sort values that sort strictly before this row |
Two consequences follow:
- The first rank is always 1 for both functions.
- The highest
DENSE_RANKin a partition equals the number of distinct sort values. The highestRANKcan equal the number of rows.
How ties are decided with several sort columns
Two rows tie only when they are equal on every expression in the window ORDER BY. Adding a second column can therefore break ties:
SELECT employee_id,
department_id,
salary,
hire_date,
RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC, hire_date
) AS rnk
FROM employees;Here two employees share a rank only if they have the same salary and the same hire date. Use this deliberately. If your business rule is "highest salary wins, and earlier hire wins a salary tie", put both columns in. If the rule is only about salary, leave hire_date out so that equal salaries stay tied.
NULLs and sort direction
In Oracle, NULL values sort last in ascending order and first in descending order. With ORDER BY commission DESC, employees with no commission receive rank 1, and all of them tie. This is rarely what you want.
SELECT employee_id,
commission_pct,
DENSE_RANK() OVER (ORDER BY commission_pct DESC NULLS LAST) AS commission_rank
FROM employees;State NULLS FIRST or NULLS LAST whenever the column can be NULL. Oracle treats all NULL values as equal for ranking, so they share one rank.
Also remember that the sort direction decides what rank 1 means. ORDER BY salary DESC makes the highest salary rank 1. ORDER BY salary makes the lowest salary rank 1.
Ranking without PARTITION BY
Leaving out PARTITION BY treats the whole result set as one partition. This ranks every row against every other row:
SELECT employee_id,
salary,
RANK() OVER (ORDER BY salary DESC) AS company_rank
FROM employees;You can mix scopes in one query. Adding a partitioned rank next to this column gives each employee a company-wide rank and a department rank at once.
Choosing between the three functions
The choice depends on how you want ties to behave in the answer you return.
| Requirement | Function |
|---|---|
| Exactly one row per number, such as picking one row per group or removing duplicates | `ROW_NUMBER` |
| Competition-style positions, where two gold medals mean no silver | `RANK` |
| The Nth distinct value, such as the second-highest salary | `DENSE_RANK` |
A common filter makes the difference visible. Suppose you want the top three salaries in each department.
SELECT department_id, employee_id, salary, drnk
FROM (
SELECT department_id,
employee_id,
salary,
DENSE_RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS drnk
FROM employees
)
WHERE drnk <= 3
ORDER BY department_id, drnk, employee_id;With DENSE_RANK, you get every employee who earns one of the three highest distinct salaries, so a department can return more than three rows. With RANK <= 3, a tie at positions 2 and 3 pushes the next rank to 4, so you could get fewer distinct salary levels. With ROW_NUMBER <= 3, you get exactly three rows, and a tied employee may be cut off arbitrarily.
The filter sits in the outer query because analytic functions cannot appear in WHERE. The inline view computes the rank first, and the outer query filters on it.
Common errors
- Missing
ORDER BYinOVER.RANK() OVER (PARTITION BY department_id)raises an error, because ranking needs an order. - Using
RANKwhen you need one row. If a ranking filter such asrnk = 1returns two rows for a department, the cause is a tie, not a bug. Switch toROW_NUMBERwith a tiebreaker if exactly one row is required. - Reading gaps as missing data. Gaps in
RANKvalues are expected. A sequence of 1, 2, 2, 4 does not mean a row was lost. - Ranking on a computed column. You cannot refer to the alias in the same
SELECTlist. Repeat the expression inside theOVERclause, or compute it in an inline view first. - Forgetting
NULLS LAST. Descending order putsNULLfirst, and all of those rows become rank 1.
Exercise
Exercise
A table has these salaries in one department: 100, 100, 90, 80, 80, 70. Using ORDER BY salary DESC, what are the RANK and DENSE_RANK values for each row, in that order? Which function would you use to find the second-highest salary value, and why?
Show answer
RANK gives 1, 1, 3, 4, 4, 6. DENSERANK gives 1, 1, 2, 3, 3, 4. Use DENSERANK to find the second-highest salary, because it has no gaps: DENSE_RANK = 2 selects the rows with salary 90. With RANK, no row has rank 2 here, because the tie at 100 pushes the next rank to 3.
Exercise
Write a query that returns, for each department, every employee with the highest salary in that department. Why can this return more than one row per department, and which function makes that behaviour correct?
Show answer
Use RANK (or DENSERANK) in an inline view and filter in the outer query: SELECT departmentid, employeeid, salary FROM (SELECT departmentid, employeeid, salary, RANK() OVER (PARTITION BY departmentid ORDER BY salary DESC) AS rnk FROM employees) WHERE rnk = 1. Several employees can share the top salary, and tied rows receive the same rank, so all of them have rank 1. ROW_NUMBER would return only one of them, chosen arbitrarily.