AI Hints
Home›PostgreSQL Tutorial›ROLLUP and CTEs
PostgreSQL · Lesson 28 of 120

GROUPING SETS and ROLLUP

Subtotals.

⏱ 2 min read▶ Video at 23:44🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

A sales report needs revenue per genre and year, plus a subtotal for each genre, and a grand total. Rollup adds those subtotal rows for you.

  • Genre + year
  • Subtotals
  • Grand total

Revenue with subtotals

We join items, orders and books, and sum quantity times price. Group by rollup genre, year adds a subtotal per genre and a grand total. The total rows have null in the grouped columns. Run it. Two genres, with subtotals and a total.

query.sqlsql
SELECT b.genre, extract(year FROM o.order_date) AS year,
       sum(i.quantity * b.price) AS revenue
FROM order_items i
JOIN orders o USING (order_id)
JOIN books b USING (book_id)
WHERE b.genre IN ('Cooking', 'Fantasy')
GROUP BY ROLLUP (b.genre, year)
ORDER BY b.genre, year;
Output
  genre  | year | revenue
---------+------+----------
 Cooking | 2024 |  1343.45
 Cooking | 2025 |  2419.01
 Cooking |      |  3762.46
 Fantasy | 2024 |  2540.08
 Fantasy | 2025 |  5386.97
 Fantasy |      |  7927.05
         |      | 11689.51
(7 rows)

Grouping options

Rollup gives subtotals in a hierarchy. Cube gives every combination. Grouping sets lists exactly the groupings you want. And the grouping function tells subtotal rows from real ones.

keyvalue
ROLLUPhierarchy subtotals
CUBEevery combination
GROUPING SETSpick groupings
grouping()spot subtotals

Summary

Rollup, cube and grouping sets add subtotal rows to one query. Next, making long queries readable with CTEs.

Key takeaways
  • ROLLUP
  • Subtotals
  • Grand total
Next up: CTEs — named steps