← Back to PostgreSQL Course | Chapter 7: Aggregations & Grouping | Lesson 6 of 7

GROUPING SETS

GROUPING SETS lets you compute several different groupings in one query.

In this page:

  1. GROUPING SETS
Syntax
sql
SELECT column1, column2, aggregate_function(column)
FROM table_name
GROUP BY GROUPING SETS ((column1), (column2), ());

GROUPING SETS

GROUP BY GROUPING SETS ((a), (b), ()) computes totals by a, by b and overall in a single pass.

CUBE (a, b) generates every combination of the listed columns and ROLLUP a hierarchy. Rows not belonging to a grouping have NULL in that column.

It replaces several UNION ALL queries.

Note: GROUPING SETS replaces multiple GROUP BY queries joined with UNION ALL.

Example: GROUPING SETS

bash
shop=# SELECT region, item, SUM(qty) AS total
shop-# FROM sales GROUP BY GROUPING SETS ((region), (item), ())
shop-# ORDER BY region, item;
 region | item | total
--------+------+-------
 N      |      |     8
 S      |      |    13
        | book |     4
        | lamp |     2
        | pen  |    15
        |      |    21

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Writing separate queries for each grouping
  2. Not labelling NULL placeholder rows
  3. Using CUBE on many columns
Chapter Summary
  • Several groupings in one query
  • CUBE gives all combinations
  • ROLLUP gives a hierarchy
  • Missing groups show NULL
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.