- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL CUBE
In standard SQL, the CUBE operator is a powerful extension of the GROUP BY clause. While a standard GROUP BY aggregates data based on a specific set of columns, CUBE goes much further by generating every possible combination of groupings from the columns you specify. This includes individual subtotals for every column and a final grand total for the entire result set.
Think of CUBE as a way to create a multi-dimensional "cross-tab" report using a single query. It is an essential tool for Data Analysts and Business Intelligence (BI) developers who need to look at data from multiple perspectives simultaneously.
Syntax of SQL CUBE
SELECT column_name1, column_name2, aggregate_function(column_name)
FROM table_name
GROUP BY CUBE(column_name1, column_name2);
- column_name1, column_name2: These are the dimensions you want to analyze (e.g., Region, Year, Category).
- aggregate_function(): Common math operations like
SUM()for revenue,COUNT()for orders, orAVG()for performance metrics. - CUBE(): The keyword that tells the database engine to calculate all permutations of the listed columns.
AS total_revenue) to make the resulting report easier for non-technical stakeholders to read.
Key Features of SQL CUBE
- Exhaustive Grouping: Unlike a standard GROUP BY, it doesn't just show one level; it computes subtotals for every dimension listed.
- Grand Total Included: The last row of a CUBE result set typically represents the sum of all data in the table.
- Order Independence: Unlike
ROLLUP, the order of columns insideCUBE(a, b)does not change the number of rows returned you get all combinations regardless. - Reporting Efficiency: It allows you to replace multiple
UNION ALLqueries with one clean, optimized statement.
Example of SQL CUBE
Consider the following table:
Table: Sales
Query: Compute total sales for all category and product combinations
SELECT category, product, SUM(sales_amount) AS total_sales
FROM sales
GROUP BY CUBE(category, product);
Output:
| category | product | total_sales |
|---|---|---|
| Electronics | Laptop | 1000 |
| Electronics | Phone | 700 |
| Electronics | NULL | 1700 |
| Furniture | Chair | 500 |
| Furniture | Table | 800 |
| Furniture | NULL | 1300 |
| NULL | Laptop | 1000 |
| NULL | Phone | 700 |
| NULL | Chair | 500 |
| NULL | Table | 800 |
| NULL | NULL | 3000 |
NULL in the output means missing data in the table. In a CUBE query, a NULL actually represents the "All" or "Total" value for that column.
Explanation
- Specific Groupings: The rows where both
categoryandproducthave values are your standard grouped records. - Category Subtotals: Rows where
productisNULLshow the total sales for that specific category (e.g., Electronics = 1700). - Product Subtotals: Rows where
categoryisNULLshow how much a specific product sold across all categories (e.g., Laptop = 1000). - Grand Total: The row where both columns are
NULLshows the total sales for the entire dataset (3000).
GROUPING() function to distinguish between a "natural" NULL and a "subtotal" NULL generated by CUBE.
SQL CUBE vs. SQL ROLLUP
While both operators provide subtotals, they differ in the "depth" of the analysis. ROLLUP is hierarchical (useful for Year > Month > Day), whereas CUBE is non-hierarchical and explores every possible intersection.
| Feature | CUBE | ROLLUP |
|---|---|---|
| Generates subtotals | β Yes | β Yes |
| Generates grand total | β Yes | β Yes |
| Generates all combinations | β Yes (Full Cross-section) | β No (Hierarchical only) |
| Best for multi-dimensional | β Yes | β No |
| Best for hierarchical data | β No | β Yes |
SQL CUBE with COUNT()
CUBE isn't limited to sums. It is frequently used with COUNT() to understand inventory distribution or frequency of events across multiple categories.
Example: Count the number of unique product entries in each category and overall
SELECT category, product, COUNT(*) AS product_count
FROM sales
GROUP BY CUBE(category, product);
This query helps you see not just how many items are in "Electronics," but also how many items exist in the entire inventory, all within a single result set.
Summary
- CUBE provides a comprehensive view of your data by generating every possible grouping set.
- The
NULLvalues in the output act as placeholders for subtotals and grand totals. - It is more powerful than
ROLLUP()because it calculates combinations for every column, regardless of hierarchy. - Use cases: Highly effective for financial auditing, warehouse inventory management, and creating complex business intelligence dashboards.