The UNBOUNDED PRECEDING is a windowing clause which defines the aggregation window i.e. the extent of rows to be used in aggregation. It tells oracle, the extent from where the rows are to be aggregated in the subgroup.
Syntax for the UNBOUNDED PRECEDING clause with PARTITION BY in Oracle SQL / PLSQL is:
,aggregate_function () OVER (PARTITION BY column(s) ORDER BY column(s) ROWS UNBOUNDED PRECEDING)
GROUP BY (column(s));
Using the UNBOUNDED PRECEDING clause with partition by
Suppose we have a table named ‘employee’ as shown below:
If we write our query as:
,SUM(SUM(Salary)) OVER (PARTITION BY department ORDER BY department
ROWS UNBOUNDED PRECEDING) AS TOTAL_SALARY
GROUP BY department, salary, employee_name
ORDER BY department, employee_name; [/sourcecode]
We will get the following result:
Let’s observe the records (especially the ‘Dept_Salary’ column) fetched to understand the UNBOUNDED PRECEDING clause.
- 1st and 2nd record (for Emp B and Emp C) pertain to ‘IT’ department, the Dept_salary column for the second records gives us the total of the salary being given to the ‘Emp B’ and ‘Emp C’ in ‘IT’ Department
- 3rd, 4th and 5th records (for Emp A, Emp E amd Emp F) correspond to Sales department.
- The Dept_salary column of the 4th and 5th record tells us the total of salary being given to ‘Emp A’ and ‘Emp E’ and ‘Emp A’, ‘Emp E’ and ‘Emp F’ respectively in ‘Sales’ department.
- The 6th record corresponds to ‘Emp D’ in ‘Support’ department, the Dept_salary column for this record gives the total of salary being given to ‘Emp D’in ‘Support’ department.