// aggregates reference

SQL ROLLUP clause

Adds a subtotal row for each grouping prefix plus a grand-total row.

Categoría
Aggregates
Returns
detail rows plus subtotals
In this category
39 of 52

Sintaxis

GROUP BY ROLLUP(a, b) | GROUP BY a, b WITH ROLLUP

Soporte del motor

MotorSupportNotas
SQL Server Sí Supported under this name.
PostgreSQL Sí Supported under this name.
MySQL Sí syntax differs: GROUP BY a, b WITH ROLLUP
SQLite Not built in no ROLLUP; emulate with UNION ALL of grouped queries
Oracle Sí Supported under this name.

Ejemplos

PostgreSQL

SELECT region, city, SUM(amount) FROM sales GROUP BY ROLLUP(region, city);

MySQL

SELECT region, city, SUM(amount) FROM sales GROUP BY region, city WITH ROLLUP;

Conviene saberlo

  • ROLLUP(a, b) produces (a, b), (a) and () levels: a hierarchy, not every combination; that is CUBE.
  • Subtotal rows show NULL for the rolled-up columns, colliding with real NULLs unless you add GROUPING().
  • MySQL's WITH ROLLUP is the same idea in a different position. Before 8.0.12 it could not be combined with ORDER BY; current versions allow it, and ORDER BY a puts the NULL subtotal rows first.

Questions about ROLLUP

Which row is the grand total?

The one with NULL in every rolled-up column; confirm with GROUPING(region) = 1.

What is MySQL's syntax?

GROUP BY a, b WITH ROLLUP instead of GROUP BY ROLLUP(a, b).

ROLLUP vs CUBE?

ROLLUP rolls up along the listed order only; CUBE computes every subset of the columns.

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

// 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.