Sub topic 3
Splitting Rows into Partitions with `PARTITION BY`
Prerequisites
This chapter assumes that you can write basic SELECT, WHERE, and ORDER BY queries. You should also know GROUP BY, aggregate functions such as COUNT, and inline views.
An analytic function calculates a value for each row while keeping the original rows in the result. The PARTITION BY clause divides those rows into separate groups, called partitions. The analytic calculation starts again for each partition.
For example, employee numbers can restart at 1 for every department:
WITH employees AS (
SELECT 101 employee_id, 10 department_id, 9000 salary FROM dual UNION ALL
SELECT 102, 10, 7000 FROM dual UNION ALL
SELECT 103, 20, 8500 FROM dual UNION ALL
SELECT 104, 20, 6000 FROM dual
)
SELECT employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS department_position
FROM employees
ORDER BY department_id, department_position;The PARTITION BY department_id clause creates one partition for department 10 and another for department 20. ROW_NUMBER then numbers employees separately inside each partition.
| employee_id | department_id | salary | department_position |
|---|---|---|---|
| 101 | 10 | 9000 | 1 |
| 102 | 10 | 7000 | 2 |
| 103 | 20 | 8500 | 1 |
| 104 | 20 | 6000 | 2 |
Without PARTITION BY, all employees would belong to one set. The row numbers would be 1 through 4 across the entire result.
Partitioning is different from `GROUP BY`
GROUP BY combines rows into one result row per group. An analytic partition does not remove or combine rows. It provides the group used by the calculation, while every input row remains visible.
You can also calculate a partition total:
SELECT employee_id,
department_id,
salary,
SUM(salary) OVER (
PARTITION BY department_id
) AS department_salary_total
FROM employees
ORDER BY department_id, employee_id;Every employee in the same department receives the same department total. Because there is no window ORDER BY, the sum covers the complete partition.
Choosing partition columns
Choose columns that define the independent groups for your question. For example:
department_idranks employees within departments.customer_idcompares orders within each customer.regioncalculates totals separately for each region.
You can use more than one column. PARTITION BY region, product_id creates one partition for each region-and-product combination.
Exercise
How would you number orders from newest to oldest separately for each customer, using customer_id, order_id, and order_date?
Show answer
Use ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, order_id) so the numbering restarts for every customer and order_id provides a tiebreaker.