Sub topic 2
Anatomy of the `OVER` Clause
Assume you know basic SELECT, WHERE, and ORDER BY, plus GROUP BY, aggregate functions, and inline views. This chapter explains how the OVER clause tells an analytic function which related rows to inspect.
Analytic functions keep detail rows
An aggregate function, such as SUM, combines several rows into one result when used with GROUP BY. An analytic function calculates a value from related rows but returns a result for every original row.
For example, this query returns one row per department:
SELECT department_id,
SUM(salary) AS department_total
FROM employees
GROUP BY department_id;The analytic version keeps each employee and adds the department total:
SELECT employee_id,
department_id,
salary,
SUM(salary) OVER (PARTITION BY department_id) AS department_total
FROM employees
ORDER BY department_id, employee_id;The OVER clause defines the window, which is the set of rows used for each calculation.
The parts of `OVER`
An OVER clause can contain these main parts:
PARTITION BYdivides the result rows into independent groups.ORDER BYdefines the order of rows within each group.- A windowing clause, such as
ROWS BETWEEN, limits the rows around the current row. This chapter focuses on the first two parts.
function_name(arguments)
OVER (
PARTITION BY grouping_columns
ORDER BY ordering_columns
)PARTITION BY is optional. Without it, the entire result is one partition. ORDER BY is also optional for functions that do not need row order, such as a partition total. Ranking and neighbour functions usually need it.
Partitioning and ordering
Suppose the employees are divided into department partitions and sorted by salary from highest to lowest:
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS salary_position
FROM employees
ORDER BY department_id, salary DESC;The two ORDER BY clauses have different purposes:
| Clause | Purpose |
|---|---|
| `ORDER BY` inside `OVER` | Determines how the analytic function processes rows |
| Final `ORDER BY` | Determines how Oracle displays the complete result |
The analytic ordering can rank employees by salary, while the final ordering could instead sort by employee name.
If two employees have the same salary, Oracle may choose either one first unless the window ordering includes a tiebreaker:
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
)Here, employee_id makes the ordering deterministic, assuming it is unique.
Evaluation order
Analytic functions are calculated after FROM, WHERE, GROUP BY, and HAVING. They are calculated before the final query ORDER BY. Therefore, an analytic expression generally cannot appear directly in WHERE. Put the calculation in an inline view, then filter it in the outer query.
Exercise
What does PARTITION BY departmentid change in a ROWNUMBER expression?
Show answer
It restarts the numbering for each department instead of numbering all result rows in one sequence.