// aggregates reference

SQL GROUPING SETS clause

Computes multiple grouping levels in a single pass instead of one query per level.

Category
Aggregates
Returns
one result set per grouping level
In this category
38 of 52

Syntax

GROUP BY GROUPING SETS ((a), (b), ()) | GROUP BY GROUPING SETS ((a, b), (a), ())

Engine support

EngineSupportNotes
SQL Server Yes Supported under this name.
PostgreSQL Yes Supported under this name.
MySQL Not built in MySQL supports only WITH ROLLUP; no GROUPING SETS or CUBE
SQLite Not built in emulate with UNION ALL of grouped queries
Oracle Yes Supported under this name.

Examples

PostgreSQL

SELECT make, model, SUM(sales) FROM items_sold GROUP BY GROUPING SETS ((make, model), (make), ());

SQL Server

SELECT make, model, SUM(sales) FROM items_sold GROUP BY GROUPING SETS ((make, model), (make), ());

Good to know

  • The empty set () is the grand total row; omitted columns show placeholder NULLs, so pair the query with GROUPING or GROUPING_ID.
  • CUBE(a, b) is shorthand for all four sets of a and b; ROLLUP(a, b) is the prefix hierarchy.
  • MySQL has only WITH ROLLUP, which covers the prefix hierarchy and nothing else; SQLite has none of it. Both need UNION ALL of separate GROUP BY queries.

Questions about GROUPING SETS

GROUPING SETS vs multiple queries?

One scan and one sort instead of several; the engine computes every level together.

What does GROUPING SETS ((a), ()) mean?

Detail rows by a plus one grand-total row with a NULL.

Does MySQL support GROUPING SETS?

No, only GROUP BY ... WITH ROLLUP (MySQL 8.4 still lacks GROUPING SETS and CUBE); use UNION ALL of grouped queries for the rest.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.