Sub topic 9
Top-N per Group with an Inline View
Assume you know SELECT, WHERE, ORDER BY, GROUP BY, and inline views. An inline view is a subquery in the FROM clause. This chapter uses ROW_NUMBER to return the highest-paid employees in each department.
Why a simple WHERE clause is not enough
A top-N-per-group query finds the first few rows separately within every group. For example, you might need the three highest-paid employees in each department.
This does not work:
SELECT department_id,
employee_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS rn
FROM employees
WHERE rn <= 3;Oracle evaluates the WHERE clause before it calculates the analytic expression. At that point, rn does not exist as a column that WHERE can use. Oracle reports an invalid identifier.
Compute the row number in an inline view first. Then filter it in the outer query.
Build the query in two steps
The inner query assigns a number independently inside each department:
SELECT department_id,
employee_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS rn
FROM employeesPARTITION BY department_id starts numbering again for every department. The highest salary comes first because of salary DESC.
The outer query can now filter the calculated column:
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 result contains at most three employees per department. employee_id is a tiebreaker. It gives Oracle a stable order when two employees have the same salary.
Choosing a function for ties
ROW_NUMBER always assigns distinct numbers. If two employees tie for third place, only one receives rn = 3, so the other is excluded.
Use RANK when tied rows should share a rank and gaps should follow a tie. Use DENSE_RANK when tied rows should share a rank without gaps.
| Function | Two tied rows | Following rank |
|---|---|---|
| `ROW_NUMBER` | Different numbers | Next number |
| `RANK` | Same number | Skips numbers |
| `DENSE_RANK` | Same number | No skipped numbers |
For example, replace ROW_NUMBER() with DENSE_RANK() when you want every employee whose salary belongs to the top three distinct salary levels. The result may contain more than three rows.
Exercise
Exercise
Write a query that returns the two earliest orders for each customer from an orders table, using orderdate and orderid to make the ordering deterministic.
Show answer
SELECT customerid, orderid, orderdate FROM ( SELECT customerid, orderid, orderdate, ROWNUMBER() OVER ( PARTITION BY customerid ORDER BY orderdate, orderid ) AS rn FROM orders ) WHERE rn <= 2 ORDER BY customer_id, rn;