Sub topic 7
Handling Ties and Making Results Deterministic
Prerequisites and the tie problem
This chapter assumes you know basic SELECT, WHERE, and ORDER BY, aggregate functions, and inline views. An analytic function calculates a value for each row while keeping the original rows. Its window ORDER BY determines how rows are compared.
Suppose several employees have the same salary. If you number employees only by salary, Oracle knows that those employees are tied, but it has no required order among them. The result can change between executions or execution plans.
Choosing a ranking function
ROW_NUMBER gives every row a different number. It is useful when you need exactly one row at each position, such as exactly three employees per department. If salaries tie, a unique tiebreaker decides which employee receives the smaller number.
RANK gives tied rows the same rank and leaves gaps after the tie. DENSE_RANK also gives tied rows the same rank, but does not leave gaps.
| Function | Salaries 100, 100, 90, 80 | Typical purpose |
|---|---|---|
| `ROW_NUMBER` | 1, 2, 3, 4 | Exactly one row per position |
| `RANK` | 1, 1, 3, 4 | Competition-style ranking |
| `DENSE_RANK` | 1, 1, 2, 3 | Ranking distinct value levels |
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) 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;Here, employee_id makes ROW_NUMBER deterministic. It is not included in the RANK or DENSE_RANK expressions because adding it would make equal salaries different ordering values. That would remove the tie.
Adding a reliable tiebreaker
A tiebreaker should be stable and unique, usually a primary key. Avoid using a value that can change, such as a display name, unless that value is unique and stable.
Use ROW_NUMBER when the requirement says “three rows.” Use RANK or DENSE_RANK when the requirement says “everyone tied within the first three ranks.” The choice affects how many rows the query returns.
Also make null ordering explicit when the sort column can contain nulls. Oracle defaults to NULLS LAST for ascending order and NULLS FIRST for descending order, but writing the rule documents your intent.
Exercise
Which function should you use for exactly one employee at each position, with employee_id resolving equal salaries?
Show answer
Use ROWNUMBER() OVER (ORDER BY salary DESC, employeeid).