What are ROLLUP, CUBE, and GROUPING SETS, and when would you use them?
Last updated
They extend
GROUP BYto return detail rows plus subtotals and grand totals in one query, instead of manyUNIONqueries.ROLLUP(a, b)gives hierarchical subtotals (a,b), (a), ().CUBE(a, b)gives every combination, including (b).GROUPING SETSlists exactly the groupings you want.GROUPING()flags which rows are subtotal/total rows.
- https://www.cybrosys.com/research-and-development/postgres/how-to-use-grouping-sets-rollup-and-cube-in-postgresql
- https://blog.dailydoseofds.com/p/grouping-sets-rollup-and-cube-in
- https://medium.com/@harsh1995hg/the-advanced-sql-grouping-toolkit-mastering-rollup-cube-and-grouping-sets-2649eb952718
- https://learn.microsoft.com/en-us/sql/t-sql/queries/select-group-by-transact-sql?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/t-sql/functions/grouping-transact-sql?view=sql-server-ver17
- https://www.enterprisedb.com/postgres-tutorials/how-use-grouping-sets-cube-and-rollup-postgresql
- https://towardsdatascience.com/sql-explained-grouping-sets-rollup-and-cube-a097456fb9a2/
- https://www.sqlservertutorial.net/sql-server-basics/sql-server-rollup/