Sub topic 16
Performance considerations
This chapter assumes you can read a basic execution plan and have used ROW_NUMBER, RANK, LAG, and LEAD with PARTITION BY and ORDER BY. It covers what these functions cost, how to reduce that cost, and how to check your work.
What an analytic function costs
An analytic function needs its rows grouped by the partition key and sorted by the window ORDER BY. Oracle usually does this with a sort, shown in the plan as WINDOW SORT. The sort is the main cost. The functions themselves, such as numbering a row or reading the previous one, are cheap once the rows are in order.
The sort has three consequences:
- It needs memory. If the sorted data does not fit in the session's work area (PGA memory), Oracle spills it to temporary tablespace. Spilling is much slower than sorting in memory.
- It must see every row of the input before it can return the first row, unless an index supplies the order.
- Its cost grows with the number of rows and with the width of each row, because the sort carries every selected column.
Where the work happens
Analytic functions run after WHERE, GROUP BY, and HAVING, and before the final ORDER BY. Rows that your WHERE clause removes are never sorted. Filtering early is therefore the most effective tuning step.
Because the filter on rn happens in the outer query, Oracle cannot discard rows with a high rn before the numbering. It can still avoid a full sort in one common case, covered under top-N queries below.
Filter before the window
Put every condition that does not depend on the computed value inside the inline view, next to the data. Compare these two shapes:
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'
AND department_id IN (10, 20, 30)
)
WHERE rn <= 3
ORDER BY department_id, rn;The WHERE inside the view reduces the sorted set. Be careful about meaning here. Filtering on hire_date before numbering gives the top three among recent hires. Filtering after numbering would give recent hires who are in the overall top three. These are different questions, so choose the filter position by the question you are answering, not only by speed.
A filter on the partition column is different. A condition such as department_id IN (10, 20, 30) only removes whole partitions, so it does not change the numbering within the remaining partitions. Oracle can often push such a predicate into the view itself, even when you write it in the outer query. Filters on other columns change the numbering, so Oracle cannot move them.
Share one sort across several functions
Each distinct combination of PARTITION BY and ORDER BY can force its own sort. Functions that use identical window specifications can share one.
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC, employee_id) AS rn,
LAG(salary) OVER (PARTITION BY department_id ORDER BY salary DESC, employee_id) AS next_higher_salary
FROM employees;Both functions use the same specification, so one sort can serve both. If the second function used ORDER BY hire_date, Oracle would need a second sort over the same rows. When you have a choice, align the specifications. Write them identically, including the tiebreaker, because a small textual difference can mean a different sort.
Let an index supply the order
If a suitable index returns rows already in partition and order sequence, Oracle can skip the sort and show WINDOW NOSORT in the plan. The index must start with the partition columns, followed by the window order columns in the same directions.
CREATE INDEX emp_dept_sal_ix
ON employees (department_id, salary DESC, employee_id);This index can match the window PARTITION BY department_id ORDER BY salary DESC, employee_id. It helps most when the query reads a large share of the table through the index and needs few other columns. If the query needs many columns that the index lacks, Oracle must visit the table for each row. A full table scan plus a sort can then be cheaper, and the optimizer may choose it. An index is a candidate for the optimizer, not a guarantee, and every index adds cost to inserts and updates.
Top-N queries
For top-N per group with ROW_NUMBER() ... WHERE rn <= N, Oracle can use an optimization that keeps only the best N rows per partition while sorting. The plan shows WINDOW SORT PUSHED RANK. This avoids fully ordering each partition and holds less data in memory. It applies when the outer filter compares the rank or row number to a constant with < or <=. It does not apply when the filter is rn = 3 or when it uses a bind expression the optimizer cannot treat as a limit.
For a single overall top-N with no partitions, FETCH FIRST n ROWS ONLY on a plain ORDER BY is simpler and can be just as fast. Use analytic functions when you need a limit per group.
LAG and LEAD versus a self-join
Before analytic functions, comparing a row with its neighbour meant a self-join. A self-join reads the table twice and needs a join condition that defines "previous", which is awkward when months are missing. LAG reads the table once and sorts once.
SELECT sales_month,
amount,
amount - LAG(amount) OVER (ORDER BY sales_month) AS change_from_prev
FROM monthly_sales
ORDER BY sales_month;In most cases this form is both shorter and faster. The final ORDER BY uses the same key as the window, so Oracle can often reuse the existing sort order instead of sorting again.
Reading the plan
Do not guess. Look at the plan and check three things: whether the step is WINDOW SORT or WINDOW NOSORT, how many rows enter it, and whether it spills to temp.
EXPLAIN PLAN FOR
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';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);EXPLAIN PLAN shows the estimated plan. To see actual row counts and memory use, run the query with the hint /*+ GATHER_PLAN_STATISTICS */ and then call DBMS_XPLAN.DISPLAY_CURSOR with the format 'ALLSTATS LAST'. Compare estimated rows with actual rows. A large gap often explains a poor plan choice, and stale optimizer statistics are a common cause.
Duplicate removal
The DELETE ... ROW_NUMBER pattern from the deduplication chapter sorts the whole table by the partition key. On a large table this is a heavy statement. Run it when load is low. Check the undo and temp space it will need, and consider an index on the duplicate key such as email. For very large tables, creating a new table with CREATE TABLE AS SELECT that keeps only rn = 1 and then swapping it in can be faster than deleting millions of rows. Test that approach against your constraints, grants, and indexes first.
Summary of tuning steps
| Goal | Action |
|---|---|
| Sort fewer rows | Put non-window filters inside the inline view |
| Avoid repeated sorts | Use identical `OVER` specifications across functions |
| Avoid the sort entirely | Create an index matching partition and order columns |
| Cheaper top-N per group | Filter with `rn <= N` and look for `PUSHED RANK` |
| Avoid double table reads | Use `LAG` or `LEAD` instead of a self-join |
| Avoid temp spills | Select fewer columns and check memory use in the plan |
Exercise
A query computes ROWNUMBER() OVER (PARTITION BY departmentid ORDER BY salary DESC, employeeid) and RANK() OVER (PARTITION BY departmentid ORDER BY hire_date). The plan shows two WINDOW SORT steps. What would you change to remove one of them, and what must you check before doing so?
Show answer
Give both functions the same PARTITION BY and ORDER BY so one sort serves both. Before changing the ORDER BY of either function, check that the new ordering still answers the business question, because ranking by hire_date and ranking by salary produce different results. If both orderings are truly needed, two sorts are unavoidable, and the alternative is an index that supplies one of the orders so that sort becomes WINDOW NOSORT.
Exercise
You filter the outer query with WHERE rn = 1 for a top-1 per group on a large table, and the plan shows no PUSHED RANK. What small change to the filter might let Oracle use the optimization, and does the result stay the same?
Show answer
Change the filter to rn <= 1. The optimization applies to comparisons that limit the number with < or <=, and rn <= 1 returns the same rows as rn = 1 because ROW_NUMBER never produces a value below 1. Confirm the change by displaying the plan again.