Sub topic 7
Handling ties and making results deterministic
This chapter assumes you can write an OVER clause with PARTITION BY and ORDER BY, and that you have seen ROWNUMBER, RANK, and DENSERANK. It covers what happens when the ORDER BY inside OVER cannot tell two rows apart, and how to make your results repeatable.
What a tie is
A tie occurs when two or more rows in the same partition have identical values in every column of the window ORDER BY. The database cannot say which row comes first, because the ordering rule gives no answer.
The three numbering functions treat ties differently:
| Function | Tied rows get | Next value after the tie |
|---|---|---|
| ROW_NUMBER | Different numbers | Continues by 1 |
| RANK | The same rank | Skips ahead |
| DENSE_RANK | The same rank | Continues by 1 |
Suppose department 10 has these salaries: 9000, 8000, 8000, 7000. The results are:
| salary | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 9000 | 1 | 1 | 1 |
| 8000 | 2 | 2 | 2 |
| 8000 | 3 | 2 | 2 |
| 7000 | 4 | 4 | 3 |
RANK and DENSERANK are deterministic when ties exist. Both tied rows always get rank 2, whatever order the database reads them in. ROWNUMBER is the function that has a problem.
Why ROW_NUMBER is nondeterministic with ties
ROW_NUMBER must give each row a unique number, so it has to put tied rows in some order. Oracle does not promise which order. The two 8000 rows might get 2 and 3 today and 3 and 2 tomorrow. A different execution plan, a new index, a parallel query, or a rebuilt table can all change the outcome.
This causes real bugs. A top-N query can return different employees on different runs. A deduplication step can delete the row you wanted to keep.
Adding a tiebreaker
A tiebreaker is an extra column at the end of the window ORDER BY that makes every row in the partition distinct. The best choice is a primary key or another unique column. The extra column only matters when the earlier columns are equal, so it does not change the main ordering.
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS rn
FROM employees
ORDER BY department_id, rn;With employee_id as the second sort key, two employees with the same salary are always ordered by their ID. The numbering is now the same on every run.
Choose the tiebreaker to match a business rule when one exists. For example, ORDER BY salary DESC, hire_date gives the tied row with the earlier hire date the better number. Add the unique key last so that no ties can remain even if the business column also repeats.
Check that the key is unique within the partition
A tiebreaker only works if the combined sort columns are unique within each partition. If you use hire_date alone, two employees hired on the same day still tie. You can test this with a query that looks for leftover ties:
SELECT department_id, salary, hire_date, COUNT(*) AS row_count
FROM employees
GROUP BY department_id, salary, hire_date
HAVING COUNT(*) > 1;If this returns rows, the columns salary and hire_date are not enough on their own, and the window ORDER BY needs a unique column as well.
Choosing among the three functions
The right function depends on what you want a tie to mean.
- Use ROW_NUMBER when you need exactly one row per number, such as "keep one row per email" or "return exactly 3 rows per group". Add a tiebreaker.
- Use RANK when tied rows should share a place and you want the gap afterwards, as in a sports table where two second places mean no third place.
- Use DENSE_RANK when you want "the Nth highest distinct value", such as the second highest salary, with no gaps.
The choice changes how many rows a filter returns. With the salaries above, WHERE rank <= 2 using RANK returns three rows, because both 8000 rows have rank 2. The same filter on ROW_NUMBER returns exactly two rows, but which 8000 row is included depends on the tiebreaker.
SELECT department_id, employee_id, salary, rnk
FROM (
SELECT department_id,
employee_id,
salary,
RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS rnk
FROM employees
)
WHERE rnk <= 2
ORDER BY department_id, rnk, employee_id;This query can return more than two rows for a department. That is correct behavior for RANK, and it is often what a report should show, since leaving out an employee who earns the same as the second place would be unfair.
Ties in the final ORDER BY
The ORDER BY inside OVER controls only the numbering. It does not control the order of the rows in the result. Only the ORDER BY at the end of the statement does that. If you want the output in a repeatable order, sort it explicitly, and include a tiebreaker there too.
In the query above, the final clause is ORDER BY department_id, rnk, employee_id. Without employee_id, rows with equal rank could appear in either order between runs. The values would be right, but the display order would vary.
NULLs in the window ORDER BY
NULLs interact with ties as well. In Oracle, ORDER BY ... ASC places NULLs last and DESC places NULLs first. All NULLs in a partition compare as equal to each other, so they tie. If commission_pct is the sort column and many rows have NULL, RANK gives all of them the same rank, and ROW_NUMBER orders them arbitrarily.
Control this with NULLS FIRST or NULLS LAST, and add a tiebreaker:
SELECT employee_id,
commission_pct,
RANK() OVER (
ORDER BY commission_pct DESC NULLS LAST
) AS rnk,
ROW_NUMBER() OVER (
ORDER BY commission_pct DESC NULLS LAST, employee_id
) AS rn
FROM employees
ORDER BY rn;Here employees with no commission sort after those with one, so they do not take the top places.
How the numbering unfolds
The diagram shows how the three functions process a tie.
Common errors
- Relying on the output order. A query without a final ORDER BY has no guaranteed row order, even if the window ORDER BY looks sensible.
- Using a non-unique tiebreaker. A date or a name can repeat. End the list with a primary key.
- Expecting RANK to return exactly N rows. A filter on RANK or DENSE_RANK can return more than N rows when ties exist.
- Expecting DENSE_RANK to give a row count. DENSE_RANK of 3 means the third distinct value, not the third row.
- Forgetting NULL placement. A descending sort on a nullable column puts NULLs at the top unless you write
NULLS LAST.
Summary
Ties are harmless for RANK and DENSERANK because they give tied rows the same value. They are a hazard for ROWNUMBER, because Oracle picks an arbitrary order among tied rows. Add a unique column at the end of the window ORDER BY, and add a matching tiebreaker to the final ORDER BY, so that results do not change between runs.
Exercise
The table orders has columns orderid (primary key), customerid, and orderdate. Several orders for the same customer share the same orderdate. Write a query that returns the most recent order for each customer, so that the same order is returned on every run.
Show answer
Number the rows in an inline view, using orderid as a tiebreaker, then keep row 1: SELECT customerid, orderid, orderdate FROM ( SELECT customerid, orderid, orderdate, ROWNUMBER() OVER ( PARTITION BY customerid ORDER BY orderdate DESC, orderid DESC ) AS rn FROM orders ) WHERE rn = 1 ORDER BY customerid; Without order_id in the window ORDER BY, two orders on the same latest date would tie, and Oracle could return either one.
Exercise
Four rows in one partition have salaries 5000, 4000, 4000, 3000. Give the RANK and DENSERANK values for the salaries in descending order, and say how many rows `WHERE rankvalue <= 2` keeps for each function.
Show answer
RANK gives 1, 2, 2, 4. DENSE_RANK gives 1, 2, 2, 3. The filter keeps 3 rows for both functions, because both 4000 rows have the value 2 in each case.