GROUP BY — Summarising by Category
Split your data into groups and run aggregate functions on each one — this is how every category breakdown is built.
GROUP BY is like sorting your data into buckets, then counting or summing what is in each bucket.
EXERCISE
1GROUP BY — Summarising by Category
GROUP BY splits your rows into buckets based on a column value, then lets you run aggregate functions on each bucket separately.
The bucket analogy:
Imagine tipping all your orders onto a table and sorting them into piles — one pile per city. Then counting how many orders are in each pile. That is GROUP BY.
Basic GROUP BY:
-- How many orders per status?
SELECT status, COUNT(*) AS order_count
FROM orders
GROUP BY status;
-- Output:
-- status | order_count
-- pending | 234
-- shipped | 891
-- completed | 1442
-- cancelled | 67
GROUP BY with multiple aggregates:
-- Sales summary by category:
SELECT
category,
COUNT(*) AS product_count,
AVG(price) AS avg_price,
SUM(price * stock_qty) AS total_stock_value
FROM products
GROUP BY category
ORDER BY total_stock_value DESC;
GROUP BY multiple columns:
-- Orders per customer per status:
SELECT
customer_id,
status,
COUNT(*) AS count,
SUM(total) AS total_spent
FROM orders
GROUP BY customer_id, status
ORDER BY customer_id, status;
Rule — non-aggregated SELECT columns must be in GROUP BY:
-- This will ERROR (or give wrong results):
SELECT category, name, COUNT(*) -- 'name' is not aggregated
FROM products
GROUP BY category; -- 'name' not in GROUP BY
-- Fix: include name in GROUP BY, or aggregate it:
SELECT category, COUNT(*), MIN(name) AS example_product
FROM products
GROUP BY category;
Pro Tip: Every column in SELECT must either be in GROUP BY or be wrapped in an aggregate function. This is the golden rule of GROUP BY.
EXERCISE
2GROUP BY with ORDER BY and WHERE
GROUP BY, WHERE, and ORDER BY work together. Remember: WHERE filters individual rows before grouping, ORDER BY sorts the group summaries after.
Combining WHERE + GROUP BY + ORDER BY:
-- Top 5 cities by number of premium customers:
SELECT
city,
COUNT(*) AS premium_customer_count
FROM customers
WHERE is_premium = 1 -- filter rows BEFORE grouping
GROUP BY city -- group the remaining rows
ORDER BY premium_customer_count DESC -- sort the group results
LIMIT 5; -- take the top 5
Real-world example — monthly revenue:
-- Revenue per month this year:
SELECT
YEAR(order_date) AS year,
MONTH(order_date) AS month,
COUNT(*) AS order_count,
SUM(total) AS monthly_revenue,
AVG(total) AS avg_order_value
FROM orders
WHERE YEAR(order_date) = YEAR(CURDATE()) -- this year only
AND status = 'completed'
GROUP BY YEAR(order_date), MONTH(order_date)
ORDER BY year, month;
Department salary analysis:
SELECT
department,
COUNT(*) AS employee_count,
MIN(salary) AS min_salary,
MAX(salary) AS max_salary,
ROUND(AVG(salary), 0) AS avg_salary,
SUM(salary) AS total_payroll
FROM employees
WHERE is_active = 1
GROUP BY department
ORDER BY total_payroll DESC;
Pro Tip: You can GROUP BY a calculated expression too:
GROUP BY YEAR(order_date)— you don''t need a separate column. This is very useful for time-based analysis.
EXERCISE
3GROUP BY with ROLLUP
WITH ROLLUP adds extra summary rows to your GROUP BY results — giving you subtotals and a grand total without writing a second query.
The problem WITH ROLLUP solves:
Often after grouping, you also want the total across all groups. ROLLUP adds those summary rows automatically.
Basic ROLLUP:
-- Sales by region WITH a grand total row:
SELECT
region,
SUM(total) AS total_sales,
COUNT(*) AS order_count
FROM orders
GROUP BY region WITH ROLLUP;
-- Output:
-- region | total_sales | order_count
-- North | 234000 | 123
-- South | 189000 | 98
-- East | 310000 | 201
-- West | 145000 | 76
-- NULL | 878000 | 498 ← grand total row (region = NULL)
Multi-level ROLLUP:
SELECT
department,
job_title,
COUNT(*) AS headcount,
SUM(salary) AS payroll
FROM employees
GROUP BY department, job_title WITH ROLLUP;
-- Produces: department+job subtotals, then department totals, then grand total
Identifying the total rows with GROUPING():
-- Replace NULL with 'ALL' in the rollup row:
SELECT
IFNULL(region, 'ALL REGIONS') AS region,
SUM(total) AS total_sales
FROM orders
GROUP BY region WITH ROLLUP;
Pro Tip: ROLLUP adds rows where the grouped column is NULL — but this NULL means "subtotal/total", not "missing data". Use IFNULL to make your output clearer when presenting to stakeholders.
