Using grouping sets

Grouping sets are very useful if you want to run more than one aggregate at the same time. Using grouping sets can speed up aggregation because you don't have to process the data more than once.

Here is an example:

test=# SELECT x % 2, array_agg(x)          FROM generate_series(1, 4) AS x          GROUP BY ROLLUP (1);  ?column? | array_agg ----------+-----------         0 | {2,4}         1 | {1,3}           | {2,4,1,3} (3 rows) 

PostgreSQL offers more than just the ROLLUP clause. The CUBE and GROUPING SETS clauses are also supported.

Get Mastering PostgreSQL 10 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.