Sub topic 3
Splitting rows into partitions with PARTITION BY
This chapter assumes you can write SELECT, WHERE, and ORDER BY queries in Oracle SQL. It also assumes you know GROUP BY with aggregates such as SUM and COUNT, and that you have seen the basic shape of an OVER clause. Here you will look at one part of that clause, PARTITION BY. It decides which rows an analytic function looks at when it computes a value for the current row.
What a partition is
A partition is a group of rows that share the same value in one or more expressions. PARTITION BY creates these groups for an analytic function. The function is then evaluated separately inside each partition, as if each partition were its own small result set.
Unlike GROUP BY, PARTITION BY does not collapse rows. If the input has 107 rows, the output still has 107 rows. Each row carries a value computed from its partition.
A first example: aggregates as analytic functions
Most aggregate functions can also be used as analytic functions by adding an OVER clause. This makes PARTITION BY easy to see, because you can compare each row to its partition's total.
SELECT employee_id,
department_id,
salary,
COUNT(*) OVER (PARTITION BY department_id) AS dept_headcount,
ROUND(AVG(salary) OVER (PARTITION BY department_id), 2) AS dept_avg_salary,
salary - ROUND(AVG(salary) OVER (PARTITION BY department_id), 2) AS diff_from_avg
FROM employees
ORDER BY department_id, employee_id;Every employee row stays in the output. The dept_headcount and dept_avg_salary columns repeat the same value for all employees in a department. With GROUP BY department_id you would get one row per department and could not show employee_id or salary next to the average.
How the partition changes the result
The partition determines what the function sees. The same function with a different PARTITION BY gives a different answer for the same row.
| OVER clause | Rows the function sees for an employee in department 50 |
|---|---|
| `OVER (PARTITION BY department_id)` | Only rows with `department_id = 50` |
| `OVER (PARTITION BY department_id, job_id)` | Only rows with department 50 and the same job |
| `OVER ()` | Every row in the query result |
The last row of the table is the case with no PARTITION BY at all. The whole result set becomes a single partition. This is useful for grand totals next to detail rows:
SELECT employee_id,
salary,
SUM(salary) OVER () AS company_payroll,
ROUND(100 * salary / SUM(salary) OVER (), 2) AS pct_of_payroll
FROM employees
ORDER BY employee_id;Partitioning by several columns and expressions
PARTITION BY takes a comma-separated list. Rows fall in the same partition only if they match on every expression in the list.
SELECT employee_id,
department_id,
job_id,
salary,
MAX(salary) OVER (PARTITION BY department_id, job_id) AS max_in_dept_job
FROM employees
ORDER BY department_id, job_id, employee_id;You can also partition by an expression, not just a column. This query groups employees by the year they were hired:
SELECT employee_id,
hire_date,
COUNT(*) OVER (PARTITION BY EXTRACT(YEAR FROM hire_date)) AS hired_that_year
FROM employees
ORDER BY hire_date, employee_id;Different partitions in one query
Each analytic function has its own OVER clause, so one SELECT can use several partitionings at once. Oracle evaluates each distinct partitioning separately.
SELECT employee_id,
department_id,
job_id,
salary,
SUM(salary) OVER (PARTITION BY department_id) AS dept_total,
SUM(salary) OVER (PARTITION BY job_id) AS job_total,
SUM(salary) OVER () AS grand_total
FROM employees
ORDER BY employee_id;This is a common way to build reports that compare each row to several levels of context without any self-joins.
PARTITION BY with ranking functions
Ranking and numbering functions such as ROW_NUMBER restart in every partition. This is the main reason you will use PARTITION BY in later chapters.
SELECT department_id,
employee_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC, employee_id
) AS rn
FROM employees
ORDER BY department_id, rn;The first row of every department gets rn = 1. Without the PARTITION BY, numbering would run from 1 to the total row count across the whole result.
How NULLs are treated
Rows whose partition expression is NULL are placed together in one partition. This matches how GROUP BY treats NULL. In the standard HR sample data, one employee has no department. That employee forms a partition of one row, with department_id as NULL.
SELECT employee_id,
department_id,
COUNT(*) OVER (PARTITION BY department_id) AS rows_in_partition
FROM employees
WHERE department_id IS NULL
OR department_id = 10
ORDER BY department_id NULLS LAST, employee_id;If several rows have a NULL department, they all share one partition and see the same count. You do not need NVL to make this happen.
Combining PARTITION BY with GROUP BY
An analytic function runs after GROUP BY and HAVING have produced their rows. So an analytic function in a grouped query can use grouped columns and aggregates in both its arguments and its PARTITION BY.
SELECT department_id,
job_id,
SUM(salary) AS job_total,
SUM(SUM(salary)) OVER (PARTITION BY department_id) AS dept_total,
ROUND(100 * SUM(salary)
/ SUM(SUM(salary)) OVER (PARTITION BY department_id), 1) AS pct_of_dept
FROM employees
GROUP BY department_id, job_id
ORDER BY department_id, job_id;The inner SUM(salary) is the aggregate for each (department_id, job_id) group. The outer SUM(...) OVER (PARTITION BY department_id) adds those group totals across the department. The partition columns must be available at that stage, so each one must appear in the GROUP BY or be an aggregate.
Common mistakes
- Expecting fewer rows.
PARTITION BYnever removes rows. If you want one row per group, useGROUP BY, or filter the numbered rows withrn = 1. - Relying on output order. Partitioning does not sort the final result. Add an outer
ORDER BYwhenever the order matters. - Partitioning by a non-grouped column in a grouped query. In a query with
GROUP BY, thePARTITION BYexpressions must be grouped columns, aggregates, or expressions built from them. Otherwise Oracle raisesORA-00979: not a GROUP BY expression. - Confusing partition order with window order.
PARTITION BYonly defines the groups. Row order within each group is set byORDER BYinside theOVERclause, which the next chapter covers.
Exercises
Exercise
Write a query that returns employeeid, departmentid, salary, and the highest salary in the same department (as deptmaxsalary) for every employee. Then add a column that shows how far each employee's salary is below that maximum.
Show answer
SELECT employeeid, departmentid, salary, MAX(salary) OVER (PARTITION BY departmentid) AS deptmaxsalary, MAX(salary) OVER (PARTITION BY departmentid) - salary AS belowmax FROM employees ORDER BY departmentid, employeeid; Every employee row is kept. The highest-paid employee in each department has belowmax = 0.
Exercise
A query uses COUNT(*) OVER (PARTITION BY departmentid, jobid) and returns 3 for one row. What does the 3 mean, and how would the value change if you partitioned only by department_id?
Show answer
The 3 is the number of rows (employees) in the query result that have the same departmentid and the same jobid as the current row. Partitioning only by department_id puts all jobs in a department into one partition, so the count would be greater than or equal to 3. It is equal only when everyone in the department has that same job.