Using ROLLUP for Subtotals in MySQL
📖 Scenario: You work in a retail company database. You want to see total sales by category and product, including subtotals for each category and a grand total.
🎯 Goal: Create a SQL query using ROLLUP to get sales subtotals by category and product.
📋 What You'll Learn
Create a table called
sales with columns category (VARCHAR), product (VARCHAR), and amount (INT).Insert the exact rows: ('Electronics', 'TV', 100), ('Electronics', 'Radio', 50), ('Clothing', 'Shirt', 40), ('Clothing', 'Pants', 60).
Write a SELECT query that sums
amount grouped by category and product using GROUP BY ROLLUP(category, product).Ensure the query returns subtotals per category and a grand total.
💡 Why This Matters
🌍 Real World
Retail and sales databases often need subtotals and grand totals for reports. ROLLUP helps generate these summaries easily.
💼 Career
Knowing how to use ROLLUP is useful for data analysts and database developers to create clear summary reports without complex queries.
Progress0 / 4 steps