Sub topic 8
Where analytic functions are allowed and when they run
This chapter assumes basic SELECT, WHERE, ORDER BY, GROUP BY, aggregate functions, and inline views. An analytic function calculates a value for each result row using related rows. Unlike GROUP BY, it does not combine those rows into one row.
The logical processing order
Oracle logically processes a query in stages:
| Stage | What happens |
|---|---|
| `FROM` | Tables and joins produce source rows |
| `WHERE` | Rows are filtered |
| `GROUP BY` | Rows are grouped |
| `HAVING` | Groups are filtered |
| Analytic functions | Window calculations are evaluated |
| Final `ORDER BY` | The result rows are sorted |
An analytic function is usually written in the SELECT list. Oracle also permits it in the final ORDER BY clause. It cannot be used directly in WHERE, GROUP BY, or HAVING, because those clauses are processed before the analytic value exists.
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS salary_position
FROM employees
ORDER BY department_id, salary_position;The WHERE clause can filter source columns, but it cannot refer directly to salary_position:
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS salary_position
FROM employees
WHERE salary_position <= 3;This raises an invalid identifier error because the alias is created after WHERE has already run.
Filtering an analytic result
Put the analytic query in an inline view, which is a subquery in the FROM clause. The outer query can then filter the calculated column.
SELECT department_id,
employee_id,
salary,
salary_position
FROM (
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS salary_position
FROM employees
)
WHERE salary_position <= 3
ORDER BY department_id, salary_position;The inner query first numbers employees within each department. The outer query then keeps positions one through three. This pattern works for ROW_NUMBER, RANK, DENSE_RANK, LAG, and LEAD.
Common errors
Do not use an analytic function as though it were an aggregate function. COUNT(*) with GROUP BY reduces many rows to one row per group. COUNT(*) OVER (...) keeps every row and adds a count beside it.
Do not assume the analytic ORDER BY controls the displayed order. It controls how the calculation reads rows. Add a separate final ORDER BY when the output order matters.
Add a unique tiebreaker, such as employee_id, to the window ORDER BY. Without one, tied rows may receive different ROW_NUMBER values across executions.
Exercise
Why must a top-three-per-department query place ROW_NUMBER in an inline view?
Show answer
The analytic value is computed after WHERE, so an outer query must filter the value after the inner query has calculated it.