Sub topic 16
Performance Considerations for Oracle Analytic Functions
Assume you know SELECT, WHERE, ORDER BY, GROUP BY, aggregate functions, and inline views. This chapter focuses on how analytic queries use resources and how to keep them predictable.
Why analytic functions can be expensive
An analytic function returns a value for every input row, but Oracle may need to sort rows before it can calculate those values. The sort usually follows the columns in the analytic PARTITION BY and ORDER BY clauses.
For example, this query may sort employees separately within each department:
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS rn
FROM employees;The cost depends on the number of rows, the size of each row, and the ordering required. A large sort can use memory. If the available memory is insufficient, Oracle can use temporary tablespace on disk, which is slower.
The outer ORDER BY is separate from the analytic ordering. If both orderings require different sequences, Oracle may perform more work.
Filter after calculating
Oracle evaluates analytic functions after WHERE, GROUP BY, and HAVING in the same query block. Therefore, a condition cannot normally refer directly to an analytic alias in that block. To filter on the result, use 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;This query still calculates row numbers for the rows visible to the inner query. The outer filter then keeps three rows per department. For some top-N cases, Oracle can transform the query and reduce work, but you should confirm the plan rather than assume it.
Choose the right ranking function
ROW_NUMBER assigns a unique number to every row. RANK and DENSE_RANK preserve ties. This affects both the result size and the work needed to interpret it.
| Requirement | Suitable function |
|---|---|
| Exactly three rows per department | `ROW_NUMBER` |
| Include all employees tied at third place, with gaps after ties | `RANK` |
| Include tied positions without numbering gaps | `DENSE_RANK` |
Make ordering deterministic
If two rows have equal values in the window ORDER BY, Oracle may return them in either order. This can make ROW_NUMBER results change between executions. Add a stable, unique tiebreaker such as employee_id:
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
)Use the same principle with LAG and LEAD. An unstable order can cause a row to read a different neighbour.
Exercise
Why should a query using ROWNUMBER include employeeid after salary in the window ORDER BY?
Show answer
employee_id provides a stable tiebreaker, so rows with equal salaries receive predictable row numbers.