Construct multi-dimensional cross-tabulation matrices with CUBE, manage the 2^N explosion hazard, and specify arbitrary aggregation grains with GROUPING SETS.
Open in Present mode · 400 practice questions · Live class schedule · Try the playground
Jo class mein bola, yahan nukte mein likha hai.
What I said in class, written here as key points.
Construct multi-dimensional cross-tabulation matrices with CUBE, manage the 2^N explosion hazard, and specify arbitrary aggregation grains with GROUPING SETS.
From linear hierarchical subtotals to multi-dimensional cross-tabulations
Transitioning from single-direction hierarchies to multidimensional cross-tabulations
ROLLUP(A, B) produces 3 hierarchical sets: (A, B), (A), and (). CUBE(A, B) produces all 2^2 = 4 combinatorial sets: (A, B), (A), (B), and (). Use GROUPING SETS when you only need specific combinations without exponential growth.SELECT store_id, payment_mode_id, COUNT(*) AS orders, ROUND(SUM(net_total), 2) AS rev, CASE GROUPING(store_id, payment_mode_id) WHEN 3 THEN 'Grand Total' WHEN 2 THEN 'Payment Total' WHEN 1 THEN 'Store Total' ELSE 'Detail' END AS level FROM sales.orders WHERE store_id <= 2 AND payment_mode_id <= 2 GROUP BY CUBE (store_id, payment_mode_id) ORDER BY 1 NULLS LAST, 2 NULLS LAST; -- Single pass evaluates all 4 matrix perspectives
CUBE. When you need only specific combinations, use surgical GROUPING SETS.Understanding the mathematical transition from hierarchies to multidimensional cubes.
GROUPING SETS lets you declare the exact 3 or 4 grains you need, bypassing exponential bloat.Click perspectives below to observe how CUBE computes intersecting cross-tabulation totals.
CUBE(A, B) and CUBE(B, A) generate identical mathematical grouping sets because all combinations are computed.Generating all dimensional permutations for complete business intelligence matrices.
CUBE (A, B) expands to:
GROUP BY GROUPING SETS ( (A, B), (A), (B), () )Notice that both (A) and (B) subtotals are generated!
SELECT store_id, payment_mode_id, COUNT(*) AS total_orders, ROUND(SUM(net_total), 0) AS total_revenue FROM sales.orders WHERE store_id IN (1, 2) AND payment_mode_id IN (1, 2) GROUP BY CUBE (store_id, payment_mode_id) ORDER BY store_id NULLS LAST, payment_mode_id NULLS LAST LIMIT 15;
Click column counts below to observe how CUBE complexity escalates exponentially.
work_mem, temporary spill files flood the disk, degrading query speed 100×.GROUPING SETS instead.Architectural limits, work_mem constraints, and query optimization for CUBE queries.
WHERE clause filters before invoking CUBE. Cubing 1,000 filtered rows takes milliseconds; cubing 1,50,000 rows takes seconds.SET LOCAL work_mem = '64MB';SELECT dept_id, role, COUNT(*) AS employee_count, SUM(salary) AS total_payroll FROM stores.employees WHERE dept_id IN (1, 2) GROUP BY CUBE (dept_id, role) ORDER BY dept_id NULLS LAST, role NULLS LAST LIMIT 15;
Click execution modes below to contrast naive UNION ALL queries against native GROUPING SETS.
NULL::VARCHAR AS order_status.Explicitly declaring multiple aggregation dimensions within a single SQL statement.
GROUPING SETS (...) defines one aggregation target. You specify exactly the combinations you need, nothing more:
GROUP BY GROUPING SETS ( (store_id, status), (store_id), () )
SELECT store_id, order_status, COUNT(*) AS total_orders, ROUND(SUM(net_total), 0) AS total_revenue FROM sales.orders WHERE store_id IN (1, 2) GROUP BY GROUPING SETS ( (store_id, order_status), (store_id), () ) ORDER BY store_id NULLS LAST, order_status NULLS LAST LIMIT 15;
Click aggregation grains below to understand why () represents the global apex total.
() means: partition the table by zero columns. All rows belong to a single global partition!GROUPING SETS ( () ) produces the exact same single-row total as running SELECT COUNT(*), SUM(revenue) FROM orders without any GROUP BY clause.() row, every dimension column evaluates to NULL because all dimensions have been collapsed.How empty parentheses define whole-table grand totals alongside detailed groups.
GROUP BY GROUPING SETS ( (dept_id), () )
SELECT dept_id, COUNT(*) AS total_staff, SUM(salary) AS total_payroll FROM stores.employees WHERE dept_id IN (1, 2) GROUP BY GROUPING SETS ( (dept_id), () ) ORDER BY dept_id NULLS LAST LIMIT 10;
Six critical traps when constructing multi-dimensional cross-tabulations in production.
GROUPING SETS (a, b) instead of GROUPING SETS ((a), (b)). In PostgreSQL, missing internal parentheses is a syntax error!GROUPING SETS (store_id, ()) without enclosing (store_id). Each grouping set must be wrapped in its own parentheses tuple.customer_id). CUBE is designed for low-cardinality categorical dimensions!NULLS LAST in ORDER BY. Generated subtotal NULLs float to the top of the report, confusing business readers.High-frequency technical questions asked at Snowflake, Databricks, and Tier-1 analytics rounds.
[(A,B,C), (A,B), (A), ()], while CUBE produces 8 sets [(A,B,C), (A,B), (A,C), (B,C), (A), (B), (C), ()].Click any card to flip and verify your understanding of CUBE and GROUPING SETS.
Core architectural rules for multidimensional OLAP aggregation in PostgreSQL.
() collapses all partitions into a single company-wide grand total row matching full-table aggregate functions.Authoritative PostgreSQL syntax patterns for multidimensional cross-tabulations.
SELECT store_id, payment_mode_id, COUNT(*) AS cnt FROM sales.orders WHERE store_id IN (1, 2) AND payment_mode_id IN (1, 2) GROUP BY CUBE (store_id, payment_mode_id) ORDER BY store_id NULLS LAST, payment_mode_id NULLS LAST LIMIT 10;
SELECT dept_id, role, COUNT(*) AS cnt FROM stores.employees WHERE dept_id IN (1, 2) GROUP BY CUBE (dept_id, role) ORDER BY dept_id NULLS LAST, role NULLS LAST LIMIT 10;
SELECT store_id, order_status, COUNT(*) AS cnt FROM sales.orders WHERE store_id IN (1, 2) GROUP BY GROUPING SETS ( (store_id, order_status), (store_id), () ) ORDER BY store_id NULLS LAST, order_status NULLS LAST LIMIT 10;
SELECT dept_id, COUNT(*) AS cnt, SUM(salary) AS payroll FROM stores.employees WHERE dept_id IN (1, 2) GROUP BY GROUPING SETS ( (dept_id), () ) ORDER BY dept_id NULLS LAST LIMIT 10;
Solidify your multi-dimensional matrix mastery with these 4 production challenges on RetailMart.
sales.orders for stores 1 and 2 across payment modes 1 and 2, group by CUBE (store_id, payment_mode_id). Confirm output returns exactly 9 rows (4 cells, 2 store totals, 2 mode totals, 1 apex total) accounting for 392 orders and ₹3.27 crore revenue.stores.employees for stores 1, 2, 3 and departments 1, 2, produce a full cross-matrix calculating headcount and total payroll across store and department margins simultaneously.GROUPING SETS query for (store_id, order_status), (store_id), and (), verifying the engine computes exactly 3 grains in a single table scan.stores.employees, group by GROUPING SETS ((dept_id, role), (dept_id), ()), evaluating department-level role breakdowns, department subtotals, and corporate apex headcount.Track your progress across the complete 59-session curriculum.
Connecting normalized relational tables across primary and foreign key boundaries.