Sub topic 9
Top-N per group with an inline view
This chapter assumes you can write an Oracle query with PARTITION BY and ORDER BY inside OVER. It also assumes you know what ROW_NUMBER, RANK and DENSE_RANK return, and that you can read an inline view (a subquery in the FROM clause). Here you combine those pieces to answer a very common question: "Who are the top three earners in each department?"
Why a plain WHERE does not work
A natural first attempt filters on the number directly:
SELECT department_id, employee_id, salary
FROM employees
WHERE ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) <= 3;Oracle rejects this with ORA-30483: window functions are not allowed here. A second attempt uses the alias in the same query block:
SELECT department_id, employee_id, salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
FROM employees
WHERE rn <= 3;This fails with ORA-00904: "RN": invalid identifier. Both errors have the same cause, which is the order in which Oracle evaluates a query block.
Evaluation order explains the pattern
Within one query block Oracle works in this order:
FROMand joinsWHEREGROUP BYandHAVING- Analytic functions
SELECTlist aliases become available, then the query'sORDER BY
When WHERE runs, the analytic value does not exist yet. The alias rn is also not visible at that step. The solution is to compute the number in one query block and filter it in another. The inner block is the inline view. The outer block sees rn as an ordinary column.
The basic pattern
SELECT department_id, employee_id, salary, rn
FROM (
SELECT department_id,
employee_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS rn
FROM employees
)
WHERE rn <= 3
ORDER BY department_id, rn;The parts have these jobs:
PARTITION BY department_idrestarts the numbering for each department.ORDER BY salary DESC, employee_iddecides who is number 1. Theemployee_idcolumn breaks ties so the result is the same on every run.- The outer
WHERE rn <= 3keeps the first three rows of each partition. - The outer
ORDER BYis still required. Neither the inline view nor the windowORDER BYguarantees the order of the final result.
Oracle does not require an alias on an inline view, so the example omits one. If you join the view to another table, give it an alias such as ranked.
Choosing ROW_NUMBER, RANK or DENSE_RANK
The three functions give different answers when salaries tie. To see this, use a small self-contained data set. The WITH clause below builds it from dual, so you can run it in any schema.
WITH employees (employee_id, department_id, salary) AS (
SELECT 101, 10, 9000 FROM dual UNION ALL
SELECT 102, 10, 8000 FROM dual UNION ALL
SELECT 103, 10, 8000 FROM dual UNION ALL
SELECT 104, 10, 8000 FROM dual UNION ALL
SELECT 105, 10, 7000 FROM dual UNION ALL
SELECT 201, 20, 6000 FROM dual UNION ALL
SELECT 202, 20, 5500 FROM dual
)
SELECT department_id, employee_id, salary, rn, rnk, drnk
FROM (
SELECT department_id,
employee_id,
salary,
ROW_NUMBER() OVER (PARTITION BY department_id
ORDER BY salary DESC, employee_id) AS rn,
RANK() OVER (PARTITION BY department_id
ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (PARTITION BY department_id
ORDER BY salary DESC) AS drnk
FROM employees
)
ORDER BY department_id, rn;For department 10 the numbers are:
| employee_id | salary | rn | rnk | drnk |
|---|---|---|---|---|
| 101 | 9000 | 1 | 1 | 1 |
| 102 | 8000 | 2 | 2 | 2 |
| 103 | 8000 | 3 | 2 | 2 |
| 104 | 8000 | 4 | 2 | 2 |
| 105 | 7000 | 5 | 5 | 3 |
Filtering on <= 3 returns a different set of rows for each function:
| Filter | Rows returned for department 10 | Meaning |
|---|---|---|
| `rn <= 3` | 101, 102, 103 | Exactly three rows. Employee 104 is cut off, though tied with 102 and 103. |
| `rnk <= 3` | 101, 102, 103, 104 | Everyone whose rank is 3 or better. Can return more than three rows. |
| `drnk <= 3` | 101, 102, 103, 104, 105 | Everyone with one of the three highest distinct salaries. |
Pick the function from the business question:
- Use
ROW_NUMBERwhen you need exactly N rows per group, such as "show three rows per department on a dashboard." Add a tiebreaker so the choice among tied rows is stable and documented. - Use
RANKwhen tied rows must all be treated alike and gaps in ranking are acceptable, such as "everyone in the top three places." - Use
DENSE_RANKfor "the top three salary levels," where all employees at each level are included.
Filtering before and after numbering
Where you put a filter changes the answer. A condition in the inner WHERE removes rows before they are numbered. A condition in the outer WHERE removes rows after numbering.
SELECT department_id, employee_id, salary, rn
FROM (
SELECT department_id,
employee_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS rn
FROM employees
WHERE hire_date >= DATE '2020-01-01'
)
WHERE rn <= 3
ORDER BY department_id, rn;This returns the top three among employees hired since 2020. If the date condition were in the outer query instead, Oracle would first find the top three overall per department and then discard those hired earlier. Some departments would return fewer than three rows. The first form is usually what "top three among recent hires" means.
Getting extra columns
The inline view should carry every column the outer query needs. To show department names, join after numbering so the join does not multiply the rows you are ranking:
SELECT d.department_name, r.employee_id, r.salary, r.rn
FROM (
SELECT department_id,
employee_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS rn
FROM employees
) r
JOIN departments d ON d.department_id = r.department_id
WHERE r.rn <= 3
ORDER BY d.department_name, r.rn;Common errors
- Using
rnin theWHEREof the same block raisesORA-00904. Move the numbering into an inline view. - Putting the analytic function itself in
WHERE,GROUP BYorHAVINGraisesORA-30483. - Leaving out the outer
ORDER BYcan return rows in any order. - Omitting
PARTITION BYnumbers the whole result set once, which gives a global top N instead of a top N per group. - Choosing
RANKand expecting exactly N rows. Ties at the cutoff return extra rows. - Putting a filter in the outer query when it should apply before numbering. The groups then come back short.
Performance notes
The window step has to sort or otherwise order the rows in each partition. When the outer query filters on rn <= N, Oracle can often stop early and keep only the best N rows per partition. In an execution plan this shows up as a WINDOW (SORT PUSHED RANK) step. This optimization is only available when the filter compares the numbering column to a constant. Wrapping the column in an expression can hide the filter from the optimizer.
An index whose leading columns match the partition and order columns, such as (department_id, salary), can reduce the sorting. Check the plan with EXPLAIN PLAN instead of assuming it.
Exercise
A table orders(order_id, customer_id, order_date, total) holds many orders per customer. Write a query that returns each customer's two most recent orders. If two orders share the same order_date, the one with the higher order_id counts as more recent. Why can't you put the numbering function directly in the WHERE clause?
Show answer
SELECT customerid, orderid, orderdate, total FROM ( SELECT customerid, orderid, orderdate, total, ROWNUMBER() OVER ( PARTITION BY customerid ORDER BY orderdate DESC, orderid DESC ) AS rn FROM orders ) WHERE rn <= 2 ORDER BY customerid, rn; The analytic function is evaluated after WHERE, so its value does not exist when WHERE runs, and the alias rn is not visible in the same block. Computing it in an inline view lets the outer WHERE filter it as an ordinary column. The orderid tiebreaker makes the result deterministic.