Sub topic 1
Analytic Functions versus Aggregate Functions
Prerequisites
You should know basic SELECT, WHERE, and ORDER BY clauses. You should also understand GROUP BY, aggregate functions such as SUM and COUNT, and inline views, which are subqueries in the FROM clause.
Two Ways to Calculate from Related Rows
An aggregate function combines several input rows into one result. For example, SUM(salary) calculates a total. When you use it with GROUP BY, Oracle returns one row for each group.
An analytic function calculates from related rows but returns a value for every input row. It does not collapse the rows. In Oracle, an analytic function usually has an OVER clause.
Compare these queries:
SELECT department_id,
SUM(salary) AS department_total
FROM employees
GROUP BY department_id
ORDER BY department_id;This query returns one row per department. The individual employees are no longer present in the result.
SELECT employee_id,
department_id,
salary,
SUM(salary) OVER (
PARTITION BY department_id
) AS department_total
FROM employees
ORDER BY department_id, employee_id;This query returns one row per employee. Each row also shows the total salary for that employee's department.
The PARTITION BY clause divides the rows used by the analytic calculation. It does not remove or group the output rows. You can think of it as defining a separate calculation area for each department.
| Query feature | Aggregate function | Analytic function |
|---|---|---|
| Output rows | Can reduce many rows to one row per group | Keeps one output row for each input row |
| Group definition | `GROUP BY` | `PARTITION BY` inside `OVER` |
| Typical use | Totals, counts, and averages | Totals beside detail, rankings, and comparisons |
The Working Model
Oracle logically processes an analytic function after the rows have been selected and grouped. This lets the function use the result rows while preserving their detail.
For example, the following query first selects employees and then calculates the overall average salary beside every employee:
SELECT employee_id,
department_id,
salary,
AVG(salary) OVER () AS company_average
FROM employees
ORDER BY employee_id;An empty OVER() means that all selected rows belong to one analytic set. The result repeats the same company average on every row.
A common mistake is expecting an analytic function to filter rows directly:
SELECT employee_id,
salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS salary_position
FROM employees
WHERE salary_position <= 3;This is invalid because the WHERE clause is evaluated before the analytic value exists. Calculate the value in an inline view, then filter it in an outer query.
Exercise
Which approach should you use to show each employee's salary together with the average salary in that employee's department?
Show answer
Use an analytic function such as AVG(salary) OVER (PARTITION BY department_id), because it preserves each employee row.