Sub topic 1
Analytic Functions versus Aggregate Functions
An aggregate function such as AVG or SUM reduces many rows to one value. An analytic function computes a value from a set of related rows but keeps every input row in the result. This chapter explains that difference and the rules that follow from it. Later chapters cover ROW_NUMBER, RANK, LAG, and LEAD in detail.
Prerequisites
This chapter assumes you can do the following:
- Write
SELECT,WHERE, andORDER BYqueries in Oracle SQL. - Use
GROUP BYwith aggregate functions such asSUM,COUNT, andAVG. - Read an inline view, which is a subquery in the
FROMclause.
The examples use this small employees table:
| employee_id | name | department_id | salary |
|---|---|---|---|
| 1 | Ann | 10 | 5000 |
| 2 | Bob | 10 | 4000 |
| 3 | Cy | 20 | 6000 |
| 4 | Di | 20 | 6000 |
| 5 | Eli | 20 | 3000 |
The limit of GROUP BY
Suppose you want each employee's salary next to the average salary of their department. GROUP BY collapses each department into one row:
SELECT department_id,
COUNT(*) AS headcount,
AVG(salary) AS dept_avg
FROM employees
GROUP BY department_id
ORDER BY department_id;The result has two rows, one per department:
| department_id | headcount | dept_avg |
|---|---|---|
| 10 | 2 | 4500 |
| 20 | 3 | 5000 |
The individual employees are gone. If you add salary or employee_id to the select list, Oracle raises ORA-00979: not a GROUP BY expression. That error is the grouping rule at work. Once rows are grouped, every select-list item must be a grouping column or an aggregate.
The traditional workaround is to join the table to its own aggregate, which needs a second pass over the data and extra join syntax. Analytic functions remove that need.
What an analytic function does
An analytic function looks like an aggregate followed by an OVER clause. The OVER clause says which rows to look at for each result row.
SELECT employee_id,
department_id,
salary,
AVG(salary) OVER (PARTITION BY department_id) AS dept_avg,
salary - AVG(salary) OVER (PARTITION BY department_id) AS diff_from_avg
FROM employees
ORDER BY employee_id;All five employees are returned, each with the average of their own department:
| employee_id | department_id | salary | dept_avg | diff_from_avg |
|---|---|---|---|---|
| 1 | 10 | 5000 | 4500 | 500 |
| 2 | 10 | 4000 | 4500 | -500 |
| 3 | 20 | 6000 | 5000 | 1000 |
| 4 | 20 | 6000 | 5000 | 1000 |
| 5 | 20 | 3000 | 5000 | -2000 |
For each row, Oracle collects the rows in the same department, computes the average, and attaches the result to the current row. No rows are removed, so the row count stays the same as in the source table.
Three ways to see the difference
| Aspect | Aggregate with GROUP BY | Analytic function |
|---|---|---|
| Rows returned | One per group | One per input row |
| Detail columns in select list | Only grouping columns | Any column |
| How the rows are chosen | `GROUP BY` clause | `OVER` clause |
| Can the same query use different groupings? | No, one grouping per query level | Yes, each function has its own `OVER` |
The last row of the table matters in practice. One query can mix department averages, company-wide totals, and a running total, because each function carries its own OVER clause:
SELECT employee_id,
department_id,
salary,
AVG(salary) OVER (PARTITION BY department_id) AS dept_avg,
AVG(salary) OVER () AS company_avg,
SUM(salary) OVER (ORDER BY employee_id) AS running_total
FROM employees
ORDER BY employee_id;An empty OVER () means the whole result set is one partition, so company_avg is 4800 on every row. Adding ORDER BY inside OVER makes the function work cumulatively, so running_total is 5000, 9000, 15000, 21000, and 24000. The exact window that ORDER BY creates is covered in a later chapter.
Aggregate and analytic forms of the same function
Many functions come in both forms. The name tells you nothing. The presence of OVER does.
| Function | As an aggregate | As an analytic |
|---|---|---|
| `SUM`, `AVG`, `COUNT`, `MIN`, `MAX` | `SUM(salary)` with `GROUP BY` | `SUM(salary) OVER (...)` |
| `ROW_NUMBER`, `RANK`, `DENSE_RANK` | Not available | Analytic only, `OVER` required |
| `LAG`, `LEAD` | Not available | Analytic only, `OVER` required |
ROW_NUMBER, RANK, DENSE_RANK, LAG, and LEAD only make sense per row, so they have no aggregate form. Leaving out OVER for these functions is a syntax error.
When analytic functions are evaluated
Analytic functions are computed late in query processing. Oracle applies FROM, WHERE, GROUP BY, and HAVING first, then evaluates the analytic functions on the rows that remain, and finally applies the outer ORDER BY. Three consequences follow.
- Filters in
WHERErun before the analytic function. Rows removed byWHEREdo not take part in the partition's calculation. - You cannot filter on an analytic result in the same query block. The result does not exist yet when
WHEREruns. - Analytic functions are allowed only in the select list and the final
ORDER BY.
The first consequence is easy to overlook. Compare these two queries:
SELECT employee_id, salary,
AVG(salary) OVER () AS company_avg
FROM employees
WHERE department_id = 20;Here company_avg is 5000, the average of department 20 only, because WHERE has already discarded the other rows. The name is misleading. If you want the real company average on those rows, compute the analytic function in an inline view first and filter in the outer query:
SELECT employee_id, salary, company_avg
FROM (
SELECT employee_id,
department_id,
salary,
AVG(salary) OVER () AS company_avg
FROM employees
)
WHERE department_id = 20;Now company_avg is 4800 on all three rows. This inline-view pattern is the standard way to filter on analytic results, and the top-N chapter builds on it.
Combining GROUP BY with analytic functions
A query may use both. GROUP BY runs first and produces one row per group, and then the analytic function runs over those grouped rows. In that case the analytic function's argument must be a grouping column or an aggregate expression:
SELECT department_id,
SUM(salary) AS dept_total,
SUM(SUM(salary)) OVER () AS company_total
FROM employees
GROUP BY department_id
ORDER BY department_id;The inner SUM(salary) is the aggregate, evaluated per department. The outer SUM(...) OVER () is analytic and adds up the department totals. The result is two rows with dept_total 9000 and 15000, and company_total 24000 on both. This works, but the nested form is harder to read, so use it only when you need both levels in one pass.
Common mistakes
- Expecting fewer rows. An analytic function never reduces the row count. If you need one row per group, use
GROUP BY, or number rows withROW_NUMBERand filter, as shown in a later chapter. - Forgetting
OVER.AVG(salary)next to a plain column withoutGROUP BYfails withORA-00937: not a single-group group function. AddingOVER (...)turns it into an analytic. - Reading
OVER ()as "no grouping". It means one partition containing every row that survivedWHERE. - Filtering after the fact in the same block. The
WHEREclause cannot see analytic results. Use an inline view.
Exercise
The employees table above has five rows. How many rows does each query return? (a) SELECT department_id, AVG(salary) FROM employees GROUP BY department_id (b) SELECT employee_id, AVG(salary) OVER (PARTITION BY department_id) FROM employees
Show answer
(a) returns 2 rows, one per department, because GROUP BY collapses each department. (b) returns 5 rows, one per employee, because an analytic function keeps every input row and only adds a value to it.
Exercise
Write a query that returns only the employees of department 20 together with the average salary of the whole company (4800). Why does adding WHERE department_id = 20 directly to the query that computes AVG(salary) OVER () give the wrong number?
Show answer
Compute the analytic function in an inline view, then filter outside it:
SELECT employeeid, salary, companyavg
FROM (
SELECT employeeid, departmentid, salary,
AVG(salary) OVER () AS companyavg
FROM employees
)
WHERE departmentid = 20;
A WHERE in the same query block runs before the analytic function, so the other departments are removed first and the average covers only department 20 (5000).