Sub topic 1
Analytic Functions versus Aggregate Functions
Prerequisites
This chapter assumes you can write SELECT, WHERE, and ORDER BY in Oracle SQL. You should also know GROUP BY and aggregate functions such as SUM and COUNT. The examples use the employees table from the HR sample schema.
Analytic functions versus aggregate functions
An aggregate function such as SUM combines many rows into one row per group. A GROUP BY query therefore returns fewer rows than the table holds.
An analytic function computes a value for each row from a set of related rows. The output keeps every row. Oracle calls these functions analytic, and other databases often call them window functions.
Anatomy of the OVER clause
The OVER clause turns a function into an analytic function. It can contain two parts:
PARTITION BYsplits rows into independent groups.ORDER BYsets the row order inside each group.
An empty OVER () treats all rows as one group.
Splitting rows into partitions with PARTITION BY
PARTITION BY works like GROUP BY for the calculation, but it does not reduce the row count.
SELECT employee_id,
department_id,
salary,
SUM(salary) OVER (PARTITION BY department_id) AS dept_total
FROM employees
ORDER BY department_id, employee_id;Each employee row shows the total salary of that employee's department.
Ordering rows inside a partition
ORDER BY inside OVER decides the sequence that ranking and offset functions use. It does not sort the final result. Add a separate ORDER BY to the query for that.
Numbering rows with ROW_NUMBER
ROW_NUMBER assigns 1, 2, 3, and so on within each partition, in the order given by the OVER clause.
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;Exercise
The GROUP BY version of the department total query returns one row per department, but the OVER version returns one row per employee. Why?
Show answer
GROUP BY collapses all rows with the same department_id into one output row. An analytic function with PARTITION BY computes its value over the partition but returns every input row.