CUBE is an extension of GROUP BY that automatically adds all combinations of aggregations (subtotals) for the specified columns, plus a grand total. For n columns, CUBE produces 2^n grouping sets, making it ideal for multidimensional analysis similar to pivot tables in spreadsheets or OLAP cubes in data warehouses.Internally the database rewrites CUBE into GROUPING SETS, generating separate aggregate steps for each grouping set and then unions the results. NULL is placed in columns that are not part of a particular subtotal so that all results fit the same output schema. Many dialects expose the GROUPING or GROUPING_ID function to distinguish real NULLs from subtotal NULLs.CUBE is powerful but can be expensive because the number of grouping sets grows exponentially with the number of columns. Use it on low-cardinality columns or pair it with filters to reduce the result set. If you only need hierarchic subtotals, use ROLLUP instead, which is cheaper.
col1, col2, ...
(Column or expression) - Dimensions over which to compute all subtotalsGROUP BY, GROUPING SETS, ROLLUP, GROUPING, GROUPING_ID
SQL:1999
ROLLUP builds subtotals hierarchically from left to right, producing n + 1 grouping sets. CUBE generates every combination, producing 2^n grouping sets.
For n columns, CUBE returns the sum of row counts for each of the 2^n grouping sets plus one optional grand total. Actual rows depend on data cardinality.
Yes. Because CUBE calculates many grouping sets, it can consume more CPU and memory. Use it on small dimension columns or aggregate pre-filtered data.
Use the GROUPING or GROUPING_ID function. A returned value of 1 (or bit flag) indicates that the column value is a subtotal, not a real NULL.