Updated on 2026-11-06 GMT+08:00

GROUPING SETS

Function

GROUPING SETS is an extension of GROUP BY, used to implement multiple sets of grouping statistics with different granularities in a single query. It is equivalent to the result of merging multiple GROUP BY queries using UNION ALL.

Syntax

SELECT projectItem [, ...] FROM table_reference
  GROUP BY { expression | GROUPING SETS ( grouping_set [, ...] ) } [, ...]

Where grouping_set is:

{ ( expression [, ...] ) | expression }

Parameters

Parameter

Description

GROUPING SETS

Specifies multiple grouping sets. Each grouping set defines a set of columns for GROUP BY. Columns not participating in the grouping are filled with NULL in the result.

grouping_set

A grouping set, represented by a combination of columns enclosed in parentheses. Parentheses can be omitted for a single column.

GROUPING SETS Equivalent Transformation

  • GROUP BY a, b GROUPING SETS ((a,b)) is equivalent to:
    SELECT a, b, sum(expression) FROM table GROUP BY a, b;
  • GROUP BY a, b GROUPING SETS (a, b) is equivalent to:
    SELECT a, NULL, sum(expression) FROM table GROUP BY a
    UNION ALL
    SELECT NULL, b, sum(expression) FROM table GROUP BY b;
  • GROUP BY a, b GROUPING SETS ((a,b), a) is equivalent to:
    SELECT a, b, sum(expression) FROM table GROUP BY a, b
    UNION ALL
    SELECT a, NULL, sum(expression) FROM table GROUP BY a;
  • GROUP BY a, b GROUPING SETS ((a,b), a, b, ()) is equivalent to:
    SELECT a, b, sum(expression) FROM table GROUP BY a, b
    UNION ALL
    SELECT a, NULL, sum(expression) FROM table GROUP BY a
    UNION ALL
    SELECT NULL, b, sum(expression) FROM table GROUP BY b
    UNION ALL
    SELECT NULL, NULL, sum(expression) FROM table;

Precautions

  • The table to be grouped must already exist. Otherwise, an error is reported.
  • Columns not participating in the grouping are filled with NULL in the result.
  • The GROUPING() function can be used to determine whether a column participated in the grouping of the current row.

Example

Generate cross-table rows based on the group_id and job fields:

SELECT group_id, job, SUM(salary) FROM group_test
   GROUP BY group_id, job
   GROUPING SETS (group_id, job); 

Multiple grouping sets including a grand total:

SELECT group_id, job, SUM(salary), GROUPING(group_id), GROUPING(job)
   FROM group_test
   GROUP BY group_id, job
   GROUPING SETS ((group_id, job), group_id, job, ());