Explain the GROUPING() and GROUPING_ID() functions. When and why would you use them with GROUPING SETS, ROLLUP, or CUBE?
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Explain the `GROUPING()` and `GROUPING_ID()` functions. When and why would you use them with `GROUPING SETS`, `ROLLUP`, or `CUBE`?
```hint Try a column that contains NULLs
Run a `ROLLUP` on a table where the grouped column itself has NULL values, and compare the rows that come back for the NULL group and for the total.
```
```hint Think about the consumer of the result
Once the subtotal rows exist, someone has to label them, filter them and sort them. Ask what information each of those steps needs about a row.
```
### What a Strong Answer Covers
- What `GROUPING(col)` returns and the ambiguity between a subtotal NULL and a real NULL that it resolves
- How `GROUPING_ID()` combines several per-column flags into one integer, including the bit order and the values each grouping set produces
- Practical uses: labeling subtotal and total rows, keeping only some levels in `HAVING`, and sorting a report so subtotals follow their detail rows
- Dialect differences and pitfalls, such as using `COALESCE` on rolled-up columns or calling `GROUPING()` in `WHERE`
### Follow-up Questions
- Why can't `GROUPING()` appear in a `WHERE` clause, and where would you filter by grouping level instead?
- For `CUBE(region, product, channel)`, which `GROUPING_ID(region, product, channel)` value marks the rows grouped by product alone?
- How would you produce the same subtotals in a database that has no `GROUPING SETS` support?
- How would you store a `CUBE` result in a summary table so that dashboards can query one level safely?
Overview: Asks what the SQL GROUPING() and GROUPING_ID() functions return and when to use them with GROUPING SETS, ROLLUP and CUBE. It tests how subtotal rows are told apart from real NULL data, how grouping levels are encoded, and how to label, filter and sort multi-level aggregates.