Question presented to candidate:
"I want a sales report with a total per region and product, a subtotal per region, and a grand total, all in one result. What do GROUP BY ROLLUP and GROUP BY CUBE do, how are they different, and how do you tell a subtotal row from a real NULL in the data?"
What a strong answer should cover:
- Both are shorthands for grouping sets: one query that aggregates the same rows at several levels and returns all levels in one result, as if several
GROUP BYqueries were glued withUNION ALL ROLLUP (a, b)= sets(a, b),(a),(): a hierarchy of subtotals, n + 1 sets for n columns, so column order mattersCUBE (a, b)= every combination(a, b),(a),(b),(): 2^n sets, for cross-tab reports- In subtotal rows the rolled-up columns are NULL;
GROUPING(col)returns 1 there and 0 for a NULL that is really in the data, which is how you label and sort the rows - Engine support: PostgreSQL (since 9.5) and SQL Server have all three; MySQL has only
WITH ROLLUP; SQLite has none, so you emulate withUNION ALL
Clarifying questions expected:
- Which subtotal levels are needed: a hierarchy (region, then product within region) or every cross-combination?
- Can the grouping columns themselves contain NULL in the data?
Code / implementation expected: Yes β a ROLLUP query with GROUPING() used to label subtotal rows, and the UNION ALL equivalent.
Schema used by the examples: