Sub topic 5
Numbering rows with ROW_NUMBER
ROW_NUMBER assigns a sequential integer to each row of a query result, restarting the count for every group you define. This chapter covers its syntax, its behavior with ties and NULLs, and the inline-view pattern you need to filter on the number it produces.
This chapter assumes you can write SELECT, WHERE, and ORDER BY in Oracle SQL. It also assumes you know how GROUP BY and aggregates such as SUM work, and that you can read an inline view (a subquery in the FROM clause).
What ROW_NUMBER does
ROW_NUMBER is an analytic function. It looks at a set of related rows, but it returns one value per row instead of collapsing the rows as GROUP BY does. The number it returns starts at 1 and increases by 1 for each row in the ordered set. Two rows never receive the same number, even when their sort values are equal.
The general form is:
ROW_NUMBER() OVER ([PARTITION BY expr, ...] ORDER BY expr [ASC|DESC] [NULLS FIRST|LAST], ...)Three rules follow from this syntax:
- The function takes no arguments, so the parentheses after
ROW_NUMBERare always empty. PARTITION BYis optional. Without it, the whole result set is one partition.ORDER BYinsideOVERis required. Oracle raises an error if you leave it out, because the numbering has no meaning without an order.
A worked example
The examples use a small table. Run this once to create it:
CREATE TABLE emp_demo (
employee_id NUMBER PRIMARY KEY,
department_id NUMBER,
salary NUMBER
);
INSERT ALL
INTO emp_demo VALUES (101, 10, 5000)
INTO emp_demo VALUES (102, 10, 7000)
INTO emp_demo VALUES (103, 10, 7000)
INTO emp_demo VALUES (104, 20, 4000)
INTO emp_demo VALUES (105, 20, 6000)
INTO emp_demo VALUES (106, 20, NULL)
SELECT * FROM dual;
COMMIT;Now number the employees within each department, highest salary first:
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC NULLS LAST, employee_id
) AS rn
FROM emp_demo
ORDER BY department_id, rn;The result:
| EMPLOYEE_ID | DEPARTMENT_ID | SALARY | RN |
|---|---|---|---|
| 102 | 10 | 7000 | 1 |
| 103 | 10 | 7000 | 2 |
| 101 | 10 | 5000 | 3 |
| 105 | 20 | 6000 | 1 |
| 104 | 20 | 4000 | 2 |
| 106 | 20 | NULL | 3 |
Each department has its own count starting at 1. Employees 102 and 103 earn the same salary, but they still get different numbers. Only the employee_id tiebreaker decides that 102 comes first.
How partitions and order work together
PARTITION BY splits the rows into independent groups. ROW_NUMBER restarts at 1 in each group. ORDER BY inside OVER sorts the rows within each partition, and the number follows that sort.
Two points cause frequent confusion:
- The
ORDER BYinsideOVERonly controls the numbering. It does not guarantee the order of the rows the query returns. If you want the output sorted, add a normalORDER BYat the end of the statement, as the example does. - The two
ORDER BYclauses are independent. You can number by salary and display byemployee_id.
Ties make the numbering nondeterministic
When two rows have equal values in the window ORDER BY, Oracle may number them in either order. The result can differ between runs, after an index change, or after a different execution plan. A query like this one is risky:
SELECT employee_id,
salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn
FROM emp_demo;Employees 102 and 103 both earn 7000, so either could get 1 and the other 2. Anything built on that number, such as "keep row 1", can silently pick a different row on the next run.
The fix is to add tiebreaker columns until the order is fully determined. A primary key or another unique column at the end of the list guarantees a stable result:
ROW_NUMBER() OVER (ORDER BY salary DESC, employee_id)NULLs in the window ORDER BY
Oracle sorts NULLs as the largest possible value. With ascending order, NULLs come last. With DESC, NULLs come first. This affects numbering directly. Without NULLS LAST, employee 106 (salary NULL) would get number 1 in department 20 and look like the highest paid.
State the NULL position explicitly whenever the sort column can be NULL:
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC NULLS LAST, employee_id)Filtering on the row number
You cannot write this:
-- Fails with ORA-30483: window functions are not allowed here
SELECT employee_id, department_id
FROM emp_demo
WHERE ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) = 1;Oracle evaluates WHERE before it computes analytic functions. Analytic functions run after the joins, WHERE, GROUP BY, and HAVING, and before the final ORDER BY. They are only allowed in the SELECT list and in the final ORDER BY. The row number does not yet exist when WHERE runs.
To filter on it, compute it in an inline view and filter in the outer query:
SELECT department_id, employee_id, salary
FROM (
SELECT department_id,
employee_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC NULLS LAST, employee_id
) AS rn
FROM emp_demo
)
WHERE rn = 1
ORDER BY department_id;This returns the highest-paid employee in each department: 102 for department 10 and 105 for department 20. Changing rn = 1 to rn <= 3 gives the top three per department. The outer query can treat rn as an ordinary column because the inline view has already produced it.
Numbering without partitions
Leaving out PARTITION BY numbers the entire result set. This is useful for paging, where you pick a window of rows by position:
SELECT employee_id, salary
FROM (
SELECT employee_id,
salary,
ROW_NUMBER() OVER (ORDER BY employee_id) AS rn
FROM emp_demo
)
WHERE rn BETWEEN 4 AND 6
ORDER BY rn;This returns rows 4 to 6 of the list sorted by employee_id, which are employees 104, 105, and 106.
ROW_NUMBER compared with ROWNUM
ROWNUM is a pseudocolumn that Oracle assigns as it fetches rows, before any ORDER BY runs. WHERE ROWNUM <= 3 therefore takes the first three rows Oracle happens to produce, not the three highest salaries. ROW_NUMBER numbers rows after sorting them in the order you specify, and it can restart per group. Use ROWNUM for a quick unordered sample, and ROW_NUMBER whenever the order or the grouping matters.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| ORA-30483 on `WHERE` | Analytic function used in `WHERE` | Compute it in an inline view and filter outside |
| ORA-30485 missing ORDER BY expression in the window | `OVER` has no `ORDER BY` | Add an `ORDER BY` inside `OVER` |
| Different row chosen on each run | Tied values in the window `ORDER BY` | Add a unique tiebreaker column |
| A NULL row gets number 1 | `DESC` sorts NULLs first | Add `NULLS LAST` |
| Numbers do not restart per group | `PARTITION BY` missing or wrong column | Partition by the grouping column |
Exercise
Using emp_demo, write a query that returns the lowest-paid employee with a non-NULL salary in each department. Which clauses make the result deterministic and exclude the NULL salary?
Show answer
SELECT departmentid, employeeid, salary FROM ( SELECT departmentid, employeeid, salary, ROWNUMBER() OVER ( PARTITION BY departmentid ORDER BY salary ASC NULLS LAST, employeeid ) AS rn FROM empdemo ) WHERE rn = 1 ORDER BY departmentid; Ascending order with NULLS LAST puts the lowest real salary at number 1 and pushes the NULL to the end, so employee 106 is never chosen. The employeeid tiebreaker makes the order unique. The query returns employee 101 (5000) for department 10 and employee 104 (4000) for department 20.