Sub topic 5
Numbering Rows with `ROW_NUMBER`
Prerequisites
This chapter assumes that you can write basic Oracle SELECT statements, use WHERE and ORDER BY, and understand inline views. An analytic function calculates a value for each row while keeping all result rows. This differs from GROUP BY, which combines rows into one row per group.
ROW_NUMBER assigns a sequential number to each row in a defined window of rows. The numbering starts at 1.
The Basic Form
Use ROW_NUMBER with an OVER clause:
ROW_NUMBER() OVER (
[PARTITION BY group_columns]
ORDER BY sort_columns
)The ORDER BY inside OVER determines the numbering order. It is separate from the query's final ORDER BY, which controls how the result is displayed.
For example, this query numbers employees from the highest salary to the lowest salary within each department:
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS department_row
FROM employees
ORDER BY department_id, department_row;PARTITION BY department_id starts the numbering again for every department. The first employee in each department receives number 1.
Choosing a Deterministic Order
Oracle needs an ordering rule to decide which row receives each number. If two employees have the same salary, ORDER BY salary DESC alone does not specify their relative order. Oracle may number those tied rows differently on different executions.
Add a column that uniquely identifies a row, such as employee_id, as a tiebreaker:
ORDER BY salary DESC, employee_idThe first expression applies the business rule. The second expression makes the result repeatable.
A ROW_NUMBER value is always unique within its partition, even when the ordering values tie. This is different from RANK and DENSE_RANK, which are designed to give tied rows the same rank.
Top Rows in Each Group
Analytic functions are evaluated after the WHERE clause at the same query level. Therefore, you cannot normally refer to the ROW_NUMBER alias directly in that level's WHERE clause. Calculate the number in an inline view, then filter it outside:
SELECT department_id,
employee_id,
salary,
department_row
FROM (
SELECT department_id,
employee_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS department_row
FROM employees
)
WHERE department_row <= 3
ORDER BY department_id, department_row;This returns at most three employees per department. The inner query numbers every employee first. The outer query keeps only numbers 1 through 3.
Exercise
How would you return the oldest order for each customer when orders have orderid, customerid, and order_date columns?
Show answer
Number orders with ROWNUMBER() OVER (PARTITION BY customerid ORDER BY orderdate, orderid), place that query in an inline view, and filter for row_number = 1.