Sub topic 6
Ranking Rows with RANK and DENSE_RANK
Assume you know SELECT, ORDER BY, GROUP BY, and the basic OVER clause. An analytic function calculates a value for each input row without combining rows into one result.
How `RANK` and `DENSE_RANK` work
RANK assigns the same rank to rows with equal ordering values. It leaves gaps after a tie. DENSE_RANK also gives tied rows the same rank, but it does not leave gaps.
For example, suppose salaries in one department are 10,000, 10,000, 8,000, and 7,000:
| salary | `RANK` | `DENSE_RANK` |
|---|---|---|
| 10,000 | 1 | 1 |
| 10,000 | 1 | 1 |
| 8,000 | 3 | 2 |
| 7,000 | 4 | 3 |
The two employees earning 10,000 occupy two rows. Therefore, RANK assigns the next salary rank 3. DENSE_RANK counts distinct salary values, so the next rank is 2.
Ranking within departments
Use PARTITION BY to restart the ranking for each department. The ORDER BY inside OVER defines which values receive the highest rank.
WITH employees (employee_id, department_id, salary) AS (
SELECT 101, 10, 9000 FROM dual UNION ALL
SELECT 102, 10, 9000 FROM dual UNION ALL
SELECT 103, 10, 7500 FROM dual UNION ALL
SELECT 104, 10, 7000 FROM dual UNION ALL
SELECT 201, 20, 8500 FROM dual UNION ALL
SELECT 202, 20, 8000 FROM dual
)
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS row_num,
RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS salary_rank,
DENSE_RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS dense_salary_rank
FROM employees
ORDER BY department_id, salary DESC, employee_id;ROW_NUMBER always gives each row a different number. In this example, the two employees earning 9,000 can receive row numbers 1 and 2, but both receive RANK 1 and DENSE_RANK 1.
Ties and deterministic ordering
A tie exists only when all expressions in the window's ORDER BY compare equally. If you add employee_id as a second ordering expression, the rows become distinct for ranking purposes:
RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
)That produces unique ranks when employee_id is unique. Use this when you need repeatable row ordering, but do not add a tiebreaker if your business rule requires employees with equal salaries to share a rank.
Exercise
A department has salaries of 12000, 12000, 11000, and 9000. What are the RANK and DENSE_RANK values for the 9000 salary?
Show answer
RANK is 4 because two rows share rank 1. DENSE_RANK is 3 because there are three distinct salary values.