Skip to Main Content
SQL in a Nutshell, 3rd Edition
book

SQL in a Nutshell, 3rd Edition

by Kevin Kline
November 2008
Intermediate to advanced content levelIntermediate to advanced
591 pages
17h 28m
English
O'Reilly Media, Inc.
Content preview from SQL in a Nutshell, 3rd Edition

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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Effective SQL: 61 Specific Ways to Write Better SQL, First Edition

Effective SQL: 61 Specific Ways to Write Better SQL, First Edition

John L. Viescas, Douglas J. Steele, Ben G. Clothier
SQL in a Nutshell, 4th Edition

SQL in a Nutshell, 4th Edition

Kevin Kline, Regina O. Obe, Leo S. Hsu

Publisher Resources

ISBN: 9780596155322Errata Page