CUBEÂ is an extension of the GROUP BYÂ clause that generates all possible subtotal combinations for the specified columns.
Think of CUBE as:
GROUP BY on every possible combination of columns + grand total
1.Why use CUBE?
Without CUBE, you must write multiple GROUP BY queries to get totals and subtotals.
With CUBE, SQL Server does it automatically.
2.Basic Syntax
3.Example Table: Sales
| Year | Region | Amount |
|---|---|---|
| 2024 | Asia | 1000 |
| 2024 | Europe | 1500 |
| 2025 | Asia | 2000 |
| 2025 | Europe | 2500 |
4.Normal GROUP BY
✔ Only detailed totals
5.Using GROUP BY CUBE
6.Result Explanation
| Year | Region | TotalSales | Meaning |
|---|---|---|---|
| 2024 | Asia | 1000 | Year + Region |
| 2024 | Europe | 1500 | Year + Region |
| 2025 | Asia | 2000 | Year + Region |
| 2025 | Europe | 2500 | Year + Region |
| 2024 | NULL | 2500 | Year total |
| 2025 | NULL | 4500 | Year total |
| NULL | Asia | 3000 | Region total |
| NULL | Europe | 4000 | Region total |
| NULL | NULL | 7000 | Grand total |
🔹 NULL means subtotal or grand total
