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

ROLLUP

Function

ROLLUP is an extension of GROUP BY, used to generate multi-level aggregate rows, super-aggregate rows, and grand total rows. ROLLUP decreases the grouping granularity from right to left, achieving hierarchical aggregate statistics.

Syntax

SELECT projectItem [, ...] FROM table_reference
   GROUP BY ROLLUP ( expression [, ...] ) 

Or using the WITH syntax:

SELECT projectItem [, ...] FROM table_reference
   GROUP BY expression [, ...] WITH ROLLUP;

Parameters

Parameter

Description

ROLLUP

Groups and aggregates by a hierarchical structure that decreases from right to left based on the specified columns. For example, ROLLUP(a, b, c) is equivalent to GROUPING SETS ((a, b, c), (a, b), (a), ()).

expression

The grouping expression. Can be a column name or expression.

ROLLUP Equivalent Transformation

GROUP BY ROLLUP(a, b, c) is equivalent to the UNION ALL of the following four grouping queries:

  • Group subtotal for (a, b, c):
    SELECT a, b, c, sum(expression) FROM table GROUP BY a, b, c;
  • Group subtotal for (a, b):
    SELECT a, b, NULL, sum(expression) FROM table GROUP BY a, b;
  • Group subtotal for (a):
    SELECT a, NULL, NULL, sum(expression) FROM table GROUP BY a;
  • Grand total for ():
    SELECT NULL, NULL, NULL, sum(expression) FROM table;

Precautions

  • The table to be grouped must already exist. Otherwise, an error is reported.
  • The grouping granularity of ROLLUP decreases from right to left. The rightmost column is removed first.
  • The GROUPING() function can be used to determine whether a column participated in the grouping of the current row.

Examples

Generate multi-level aggregates based on group_id and job:

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

Equivalent WITH syntax:

SELECT group_id, job, SUM(salary) FROM group_test 
  GROUP BY group_id, job WITH ROLLUP; 

Use the GROUPING() function to identify the grouping level:

SELECT group_id, job, SUM(salary),
   GROUPING(group_id) AS g1, GROUPING(job) AS g2 
   FROM group_test
   GROUP BY ROLLUP (group_id, job);