Sub topic 2
Ranking rows with RANK and DENSE_RANK
This chapter assumes you know basic SELECT, WHERE, and ORDER BY in Oracle SQL, GROUP BY with aggregate functions, and inline views (subqueries in the FROM clause).
Ranking rows with RANK and DENSE_RANK
RANK and DENSERANK assign a number to each row based on the ORDER BY inside OVER. Rows with equal sort values get the same number. RANK then skips the following numbers, while DENSERANK does not.
SELECT employee_id,
department_id,
salary,
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, salary DESC;If two employees tie at 9000 for first place, RANK gives 1, 1, 3 and DENSE_RANK gives 1, 1, 2.
Handling ties and making results deterministic
ROWNUMBER always gives each row a unique number, so tied rows receive numbers in an arbitrary order. Add a unique column, such as employeeid, as a tiebreaker in the window ORDER BY:
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC, employee_id)Without the tiebreaker, the query can return different rows on different runs.
Where analytic functions are allowed and when they run
Oracle evaluates analytic functions after WHERE, GROUP BY, and HAVING, but before the final ORDER BY. You cannot use an analytic function in a WHERE clause. To filter on its result, compute it in an inline view and filter in the outer query.
Top-N per group with an inline view
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;Looking back with LAG
LAG(column) returns the value from the previous row in the window's order. The first row returns NULL.
SELECT sales_month,
amount,
LAG(amount) OVER (ORDER BY sales_month) AS prev_amount,
amount - LAG(amount) OVER (ORDER BY sales_month) AS change_from_prev
FROM monthly_sales
ORDER BY sales_month;Exercise
Using the employees table, how would you return only the top earner in each department, and which function should you use if you want to keep ties?
Show answer
Use ROW_NUMBER with an inline view and filter rn = 1 for one row per department. To keep ties, use RANK in the inline view and filter rank = 1.