Sub topic 2
Anatomy of the OVER clause
This chapter assumes you can write SELECT, WHERE, and ORDER BY in Oracle SQL, you know GROUP BY with aggregates such as SUM and COUNT, and you can use an inline view. The chapter covers the structure of the OVER clause, which is the part of the syntax that makes a function analytic. Later chapters build on it.
What OVER does
An analytic function computes a value for each row from a set of related rows, and it returns every input row. OVER marks a function as analytic and says which rows belong to that set. Without OVER, a function such as SUM is a plain aggregate. With OVER, the same function becomes analytic.
SELECT employee_id,
department_id,
salary,
SUM(salary) OVER (PARTITION BY department_id) AS dept_total,
COUNT(*) OVER () AS all_rows
FROM employees
ORDER BY department_id, employee_id;Suppose employees holds five rows. Departments 10 and 20 have three and two rows.
| employee_id | department_id | salary | dept_total | all_rows |
|---|---|---|---|---|
| 101 | 10 | 5000 | 13000 | 5 |
| 102 | 10 | 4000 | 13000 | 5 |
| 103 | 10 | 4000 | 13000 | 5 |
| 201 | 20 | 6000 | 9000 | 5 |
| 202 | 20 | 3000 | 9000 | 5 |
All five rows survive. GROUP BY department_id would have returned two. Each row carries the total of its own department and the count of the whole result.
The three parts
The general shape in Oracle is:
function_name ( arguments ) OVER (
[ PARTITION BY expr [, expr ...] ]
[ ORDER BY expr [ASC | DESC] [NULLS FIRST | NULLS LAST] [, ...] ]
[ windowing_clause ]
)The parentheses after OVER are always required. Everything inside them is optional for some functions and required for others.
PARTITION BYdivides the result into independent groups called partitions. The function is computed separately inside each one. If you omit it, the entire result set is one partition.ORDER BYorders the rows inside each partition. Ranking and offset functions need this order to mean anything. For aggregates it also changes which rows are included, as described below.- The windowing clause (
ROWSorRANGE BETWEEN ...) limits the function to a sliding or growing subset of the partition.ROW_NUMBER,RANK,DENSE_RANK,LAG, andLEADdo not accept one, so this tutorial leaves it aside.
Empty OVER and partition scope
OVER () with nothing inside means one partition holding every row of the query. That is how COUNT(*) OVER () produced 5 on every row above. It is useful for percentages of a grand total:
SELECT employee_id,
salary,
ROUND(100 * salary / SUM(salary) OVER (), 1) AS pct_of_company
FROM employees
ORDER BY employee_id;Adding PARTITION BY department_id changes the denominator to the department total, and nothing else in the query needs to change. The partition is the only thing that defines "the related rows".
A partition expression can be any expression, not only a column. PARTITION BY TRUNC(hire_date, 'YYYY') groups employees by hire year. NULL values in a partition expression form a single partition of their own, as they do in GROUP BY.
ORDER BY inside OVER is not the query's ORDER BY
The two orderings are unrelated. The ORDER BY inside OVER defines the sequence the function sees. The ORDER BY at the end of the query defines how the result is returned. Oracle makes no promise that the output is sorted by the window ordering unless you also write a final ORDER BY.
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS rn
FROM employees
ORDER BY department_id, rn;For the sample data this gives:
| employee_id | department_id | salary | rn |
|---|---|---|---|
| 101 | 10 | 5000 | 1 |
| 102 | 10 | 4000 | 2 |
| 103 | 10 | 4000 | 3 |
| 201 | 20 | 6000 | 1 |
| 202 | 20 | 3000 | 2 |
Employees 102 and 103 have the same salary. The tiebreaker employee_id fixes their order. Without it, Oracle may assign 2 and 3 to either row, and the answer can change between runs or after a different execution plan. Adding a unique column as the last sort key makes a window ordering deterministic. Chapter 7 covers ties in detail.
What requires what
Not every analytic function treats the optional parts the same way.
| Function | PARTITION BY | ORDER BY in OVER | Windowing clause |
|---|---|---|---|
| `ROW_NUMBER`, `RANK`, `DENSE_RANK` | optional | required | not allowed |
| `LAG`, `LEAD` | optional | required | not allowed |
| `SUM`, `COUNT`, `AVG`, `MIN`, `MAX` | optional | optional | optional |
For an aggregate used analytically, adding ORDER BY changes the meaning. Without it, the function covers the whole partition. With it and no explicit windowing clause, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which gives a running value:
SELECT employee_id,
department_id,
salary,
SUM(salary) OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS running_total
FROM employees
ORDER BY department_id, salary DESC, employee_id;For department 10 this returns 5000, 9000, and 13000. The first row sees only itself, the second sees two rows, and the third sees all three. The same SUM with OVER (PARTITION BY department_id) returns 13000 on every row. Because RANGE treats rows with equal sort keys as peers, tied rows would all receive the same running total. The unique employee_id in the ordering above avoids that.
Common errors
Three Oracle errors cover most beginner mistakes with OVER:
| Error | Cause | Fix |
|---|---|---|
| ORA-30484: missing window specification for this function | Writing `ROW_NUMBER()` or `RANK()` without `OVER` | Add `OVER (...)` |
| ORA-30485: missing ORDER BY expression in the window specification | A ranking or offset function with an empty or partition-only `OVER` | Add `ORDER BY` inside `OVER` |
| ORA-30483: window functions are not allowed here | An analytic function in `WHERE`, `GROUP BY`, or `HAVING` | Compute it in an inline view and filter in the outer query |
Mixing analytic functions and GROUP BY
A query can use both. GROUP BY runs first, and the analytic function then works on the grouped rows. Its arguments and OVER expressions may reference only grouped columns and aggregates:
SELECT department_id,
SUM(salary) AS dept_total,
RANK() OVER (ORDER BY SUM(salary) DESC) AS dept_rank
FROM employees
GROUP BY department_id
ORDER BY dept_rank;Here SUM(salary) is an ordinary aggregate, and RANK() then ranks the departments by that total. For the sample data, department 10 (13000) gets rank 1 and department 20 (9000) gets rank 2.
Summary of the model
Read an analytic call in this order. First, the OVER clause forms partitions. Second, the window ORDER BY sorts the rows in each partition. Third, the function runs for every row against its partition. Finally, the query's own ORDER BY arranges the output. With this model, ROW_NUMBER, RANK, LAG, and LEAD differ only in the function name and arguments before OVER.
Exercise
Using the employees table, write a query that returns employeeid, departmentid, salary, and the average salary of that employee's department as deptavg. Then change it to also show how many employees are in the whole company as companycount. Which part of OVER differs between the two new columns?
Show answer
SELECT employeeid, departmentid, salary, AVG(salary) OVER (PARTITION BY departmentid) AS deptavg, COUNT(*) OVER () AS companycount FROM employees ORDER BY departmentid, employeeid; The deptavg column uses PARTITION BY, so it is computed once per department. The company_count column uses an empty OVER (), so the whole result is a single partition. Neither column needs ORDER BY inside OVER, because aggregates do not require it, and adding one would turn them into running values.
Exercise
A colleague writes SELECT employeeid, ROWNUMBER() OVER (PARTITION BY department_id) AS rn FROM employees; and gets an error. Which error is it, and how do you fix the query so that the highest salary in each department gets 1 and ties are broken the same way every run?
Show answer
The error is ORA-30485, missing ORDER BY expression in the window specification, because ROWNUMBER needs an ordering. Fix: ROWNUMBER() OVER (PARTITION BY departmentid ORDER BY salary DESC, employeeid) AS rn. The unique employee_id after salary makes the numbering deterministic.