Partitioning

Partitioning the rows operated on by the partitioning clause is similar to using the GROUP BY expression on a standard SELECT statement. The partitioning clause takes a list of expressions that will be used to divide the result set into groups. We’ll use the following table as the basis for some examples:

SELECT * FROM odd_nums;
       NUM        ODD
---------- ----------
         0          0
         1          1
         2          0
         3          1

The following results illustrate the effects of partitioning by ODD. The sum of the even numbers is 2 (0+2), and the sum of the odd numbers is 4 (1+3). The second column of the result set reports the sum of all values in the partition to which that row belongs, yet all the detail rows are returned. The query provides summary results in the context of detail rows:

SELECT NUM, SUM(NUM) OVER (PARTITION BY ODD) S FROM ODD_NUMS;
NUM            S
---------      ----------
0              2
2              2
1              4
3              4

Not using a partitioning clause at all will sum all of the numbers in the NUM column for each row returned by the query. In effect, the entire result set is treated as a single, large partition:

SELECT NUM, SUM(NUM) OVER (  ) S FROM ODD_NUMS;
NUM            S
---------      ----------
0              6
1              6
2              6
3              6

Get SQL in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.