> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Can I use CUBE, ROLLUP or GROUPING SETS in a materialized view?

> GROUP BY modifiers work in an incremental materialized view. Store a GROUPING column in the target table so that subtotal rows do not mix with real empty or zero keys.

Yes. `WITH CUBE`, `WITH ROLLUP` and `GROUPING SETS` work in the `SELECT` of an incremental materialized view. The view computes the subtotals of every inserted block and writes them to the target table next to the detail rows. Two things make the result usable: a target table that merges the rows of different inserts, and a column that stores the grouping level, so that subtotal rows cannot be confused with detail rows.

## Example

The target table is an [`AggregatingMergeTree`](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/aggregatingmergetree) table, and the result of the [`GROUPING`](https://clickhouse.com/docs/reference/functions/aggregate-functions/grouping_function) function is the first column of its sorting key:

```sql theme={null}
CREATE TABLE visits
(
    country LowCardinality(String),
    device LowCardinality(String),
    hits UInt64
)
ENGINE = MergeTree
ORDER BY (country, device);

CREATE TABLE visits_cube
(
    grouping_id UInt64,
    country LowCardinality(String),
    device LowCardinality(String),
    hits SimpleAggregateFunction(sum, UInt64)
)
ENGINE = AggregatingMergeTree
ORDER BY (grouping_id, country, device);

CREATE MATERIALIZED VIEW visits_cube_mv TO visits_cube AS
SELECT
    grouping(country, device) AS grouping_id,
    country,
    device,
    sum(hits) AS hits
FROM visits
GROUP BY
    country,
    device
    WITH CUBE;

INSERT INTO visits VALUES
    ('DE', 'desktop', 10),
    ('DE', 'mobile', 20),
    ('FR', 'desktop', 30),
    ('', 'mobile', 100);

INSERT INTO visits VALUES ('DE', 'mobile', 5);
```

The view aggregates each `INSERT` separately, so the target table holds several rows with the same key until background merges combine them. Aggregate again when you read it:

```sql theme={null}
SELECT
    grouping_id,
    country,
    device,
    sum(hits) AS hits
FROM visits_cube
GROUP BY
    grouping_id,
    country,
    device
ORDER BY
    grouping_id,
    country,
    device;
```

```text theme={null}
    ┌─grouping_id─┬─country─┬─device──┬─hits─┐
 1. │           0 │         │ mobile  │  100 │
 2. │           0 │ DE      │ desktop │   10 │
 3. │           0 │ DE      │ mobile  │   25 │
 4. │           0 │ FR      │ desktop │   30 │
 5. │           1 │         │         │  100 │
 6. │           1 │ DE      │         │   35 │
 7. │           1 │ FR      │         │   30 │
 8. │           2 │         │ desktop │   40 │
 9. │           2 │         │ mobile  │  125 │
10. │           3 │         │         │  165 │
    └─────────────┴─────────┴─────────┴──────┘
```

`grouping(country, device)` returns a bit mask with one bit per argument, set when that key is aggregated away: `0` marks the detail rows, `1` the totals per country, `2` the totals per device and `3` the grand total. To read one level, filter on it, for example `WHERE grouping_id = 1` for the totals per country.

## Why the grouping column is needed

In a subtotal row, a key that is not part of the grouping set has the default value of its type: an empty string here, `0` for a number. A subtotal row therefore looks the same as a detail row whose key is really empty or zero. The example has such a row, a visit with an empty `country`.

Without `grouping_id`, rows 1 and 9 of the result have the same key `('', 'mobile')`, and so do rows 5 and 10. `AggregatingMergeTree` adds up rows with the same sorting key, so a target table ordered by `(country, device)` alone returns `225` hits for `('', 'mobile')` and `265` hits for `('', '')`. Neither number is a detail value or a subtotal.

## Store fewer levels

`CUBE` computes every combination of the keys, so each additional key doubles the number of grouping sets that every insert computes and stores. To store fewer levels, replace `WITH CUBE` with `WITH ROLLUP`, or list the levels you need, for example `GROUP BY GROUPING SETS ((country, device), (device), ())`.

## Alternative: NULL in subtotal rows

With the setting [`group_by_use_nulls`](https://clickhouse.com/docs/reference/settings/session-settings/group-by#group_by_use_nulls), the keys of subtotal rows are `NULL` instead of default values. To use it in a materialized view:

* add `SETTINGS group_by_use_nulls = 1` at the end of the `SELECT` of the view;
* declare the key columns of the target table as `Nullable`, for example `LowCardinality(Nullable(String))`;
* create the target table with the `MergeTree` setting [`allow_nullable_key = 1`](https://clickhouse.com/docs/reference/settings/merge-tree-settings/allow#allow_nullable_key), because its sorting key then contains `Nullable` columns.

## Related pages

* [`GROUP BY` modifiers: `ROLLUP`, `CUBE`, `GROUPING SETS`](https://clickhouse.com/docs/reference/statements/select/group-by#rollup-modifier)
* [Incremental materialized views](https://clickhouse.com/docs/concepts/features/materialized-views/incremental-materialized-view.md)
