Developer Guides, Cheat Sheets & Tools

SQL course - Part 5: GROUPING AND AGGREGATION

Part index Prerequisites Previous Next Full course

📊 PART 5 — GROUPING AND AGGREGATION


25. Aggregate functions

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟢 Beginner 20 min Count, total, and average your data · Know how NULL affects totals · Avoid the double-counting trap

[!NOTE] 📌 In plain words: An aggregate function takes many rows and squeezes them into one answer. “How many customers?” “What is the total revenue?” “What is the average order value?”

🌍 Analogy: A juicer. You put in 20 oranges (rows) and get out one glass of juice (a single value). You cannot get the oranges back — which is exactly why you cannot mix aggregated and non-aggregated columns without a GROUP BY.

25.1 🧰 The core five

Function What it does NULL handling
COUNT(*) Counts rows Counts every row, NULLs included
COUNT(col) Counts non-NULL values in that column ⚠️ Skips NULLs
COUNT(DISTINCT col) Counts unique non-NULL values Skips NULLs
SUM(col) Adds the values Skips NULLs
AVG(col) The average (mean) ⚠️ Divides by the non-NULL count
MIN(col) / MAX(col) Smallest / largest Skips NULLs; works on text and dates too
-- ✅ Works in BOTH: the shape of your data in one query
SELECT
    COUNT(*)                    AS total_products,
    COUNT(supplier_id)          AS products_with_supplier,
    COUNT(DISTINCT category_id) AS categories_used,
    SUM(units_in_stock)         AS total_units,
    AVG(unit_price)             AS avg_price,
    MIN(unit_price)             AS cheapest,
    MAX(unit_price)             AS most_expensive
FROM products;

[!WARNING] ⚠️ COUNT(*) vs COUNT(column) — the difference that catches everyone. Imagine 3 of the 18 products had no supplier (NULL): COUNT(*) would return 18, but COUNT(supplier_id) only 15. (In ShopDB every product has a supplier, so the query above shows 18 for both.) Use COUNT(*) when you mean “how many rows”. Use COUNT(column) deliberately, when you mean “how many rows actually have this value”.

[!TIP] 💡 COUNT(1) is not faster than COUNT(*). Both engines optimize them identically. Use COUNT(*) — it says what you mean.

25.2 📐 Statistical aggregates

Standard deviation and variance measure how spread out values are: a small number means the prices in a group are similar; a big number means they vary a lot.

Function 🟥 MSSQL 🟦 MySQL
Sample standard deviation STDEV(x) STDDEV_SAMP(x)
Population standard deviation STDEVP(x) STDDEV_POP(x) / STD(x)
Sample variance VAR(x) VAR_SAMP(x)
Population variance VARP(x) VAR_POP(x)
Concatenate values STRING_AGG(x, ',') GROUP_CONCAT(x)
Bitwise (via aggregation tricks) BIT_AND, BIT_OR, BIT_XOR
-- ✅ MSSQL: how consistent are our product prices within each category?
SELECT category_id, AVG(unit_price) AS avg_price, STDEV(unit_price) AS price_spread
FROM products GROUP BY category_id;
-- ✅ MySQL: same question
SELECT category_id, AVG(unit_price) AS avg_price, STDDEV_SAMP(unit_price) AS price_spread
FROM products GROUP BY category_id;

25.3 💰 Real business questions answered with aggregates

-- ✅ Works in BOTH

-- Total revenue from completed orders
SELECT
    SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS total_revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped');

-- Average order value
SELECT
    COUNT(DISTINCT o.order_id)                                AS orders,
    SUM(oi.unit_price * oi.quantity * (1 - oi.discount))      AS revenue,
    SUM(oi.unit_price * oi.quantity * (1 - oi.discount))
        / COUNT(DISTINCT o.order_id)                          AS avg_order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped');

-- Inventory value sitting on the shelves
SELECT SUM(unit_price * units_in_stock) AS inventory_value FROM products;

-- Date range of our business
SELECT MIN(order_date) AS first_order, MAX(order_date) AS latest_order FROM orders;

[!WARNING] ⚠️ The COUNT(DISTINCT o.order_id) in that second query is essential. Because we joined to order_items, an order with 3 line items appears 3 times. A plain COUNT(*) would count 36 “orders” instead of 17. Whenever you join one-to-many and then count the “one” side, you need DISTINCT.

25.4 🚫 The rule you cannot break

-- ❌ FAILS in MSSQL. Silently WRONG in MySQL without ONLY_FULL_GROUP_BY.
SELECT product_name, AVG(unit_price) FROM products;

[!NOTE] 📌 Why: AVG(unit_price) produces one value for the whole table. product_name has 18 values. SQL cannot put 18 names next to 1 average. Every column in the SELECT must either be aggregated or listed in GROUP BY.

[!WARNING] ⚠️ Old MySQL versions allowed this and returned a random product name — a nasty trap. Since MySQL 5.7, ONLY_FULL_GROUP_BY is enabled by default and it errors correctly, like every other database. Never disable that setting. Check yours:

-- 🟦 MySQL
SELECT @@sql_mode;

25.5 🎯 When to use which aggregate

Question in plain English Function ⚠️
“How many rows?” COUNT(*) Counts NULLs too — usually what you want
“How many actually have a value?” COUNT(column) Silently skips NULLs
“How many different ones?” COUNT(DISTINCT column) Expensive on big tables
“How many orders?” — after joining to items COUNT(DISTINCT o.order_id) Plain COUNT(*) counts line items, not orders
“What is the total?” SUM(column) Returns NULL, not 0, if no rows match
“What is the typical value?” AVG(column) Divides by the non-NULL count
“Biggest / smallest / earliest / latest” MAX / MIN Works on text and dates, not just numbers
“List them all in one cell” STRING_AGG 🟥 / GROUP_CONCAT 🟦 MySQL truncates at 1024 chars by default
“Does at least one exist?” EXISTS — not COUNT(*) > 0 EXISTS stops at the first hit

[!CAUTION] 🐛 Common mistake: SUM() over zero matching rows returns NULL, not 0. A dashboard tile then shows blank instead of “0”. Wrap it: COALESCE(SUM(amount), 0).

25.6 🧪 Try it yourself

  1. Find the total, average, highest, and lowest product price in one query.
  2. Count how many customers have a phone number vs how many rows exist. Explain the gap.
  3. Calculate total revenue, order count, and average order value for 2026.
  4. Find the value of all stock currently held, and the value of stock below its reorder level.

🧭 In practice — aggregate functions

How to use it. Collapse many rows into one value with COUNT, SUM, AVG, MIN, and MAX. With no GROUP BY they summarise the whole result set. Expected result: a single row of totals — the basis of every report in the guide.

When to use it. Any time the question starts with “how many”, “how much”, “what is the average”, or “what is the largest”.

Where to use it. Dashboards, reports, and data-quality checks. Scenario: SELECT COUNT(*) FROM orders WHERE status IS NULL as a nightly check. A number greater than zero means something upstream stopped setting status — a cheap query that catches a data bug before a human reports it.

When not to use it. Do not use AVG alone to describe a distribution — an average order value of £200 tells you nothing about whether that is 100 orders of £200 or 99 of £10 and one of £19,100. Report a median or percentile alongside it (§34.7). And do not aggregate across a join without checking for row multiplication first: joining orders to order_items repeats the order row per item, so SUM(order_total) silently over-counts.

Best practices. Know exactly what each one does with NULL: COUNT(*) counts rows, COUNT(column) counts non-NULL values, and SUM/AVG ignore NULLs rather than treating them as zero — which means AVG over a half-empty column answers a different question than most readers assume. COUNT(DISTINCT x) is considerably more expensive than COUNT(*); use it when you mean it.


26. GROUP BY and HAVING

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟢🟡 Beginner–Intermediate 25 min Summarize data per group · Filter groups with HAVING · Find duplicates · Avoid the three classic grouping mistakes

[!NOTE] 📌 In plain words: GROUP BY splits your rows into buckets, then runs the aggregate function once per bucket instead of once for the whole table.

🌍 Analogy: You have a pile of 500 receipts. GROUP BY store_name sorts them into piles, one per store. SUM(amount) then totals each pile separately. HAVING SUM(amount) > 1000 throws away the small piles.

Several examples in this chapter use JOIN … ON to look up matching rows in another table (for example, each product’s category name). Joins are explained fully in Chapter 28 — for now, read JOIN as “look up the matching row”.

26.1 🪣 Basic grouping

-- ✅ Works in BOTH: how many products per category?
SELECT
    category_id,
    COUNT(*)        AS product_count,
    AVG(unit_price) AS avg_price,
    MIN(unit_price) AS cheapest,
    MAX(unit_price) AS priciest
FROM products
GROUP BY category_id
ORDER BY product_count DESC;

Adding a readable name via a join:

-- ✅ Works in BOTH
SELECT
    c.category_name,
    COUNT(*)                   AS product_count,
    ROUND(AVG(p.unit_price),2) AS avg_price
FROM products AS p
JOIN categories AS c ON c.category_id = p.category_id
GROUP BY c.category_name          -- 🟥 MSSQL: also add c.category_id if you select it
ORDER BY product_count DESC;

26.2 🧩 Grouping by multiple columns

-- ✅ Works in BOTH: one bucket per unique COMBINATION
SELECT
    country,
    loyalty_tier,
    COUNT(*) AS customer_count
FROM customers
GROUP BY country, loyalty_tier
ORDER BY country, loyalty_tier;

[!NOTE] 📌 In plain words: grouping by two columns means “one row per unique pair”. ('UK','Silver') and ('UK','Bronze') are different buckets.

26.3 🗑️ HAVING — filtering the groups

-- ✅ Works in BOTH
SELECT
    c.customer_id,
    c.full_name,
    COUNT(o.order_id) AS order_count
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.full_name
HAVING COUNT(o.order_id) >= 3          -- only repeat customers
ORDER BY order_count DESC;

WHERE and HAVING together — each doing its own job:

-- ✅ Works in BOTH
SELECT
    c.category_name,
    COUNT(*)                    AS product_count,
    ROUND(AVG(p.unit_price), 2) AS avg_price
FROM products p
JOIN categories c ON c.category_id = p.category_id
WHERE p.discontinued = 0         -- 🔍 filters ROWS first (cheap)
GROUP BY c.category_name
HAVING AVG(p.unit_price) > 200   -- 🗑️ then filters GROUPS
ORDER BY avg_price DESC;
  WHERE HAVING
Filters Individual rows Whole groups
Runs Before GROUP BY After GROUP BY
Can use aggregates ❌ No ✅ Yes
Can use SELECT aliases ❌ No 🔀 MySQL yes, MSSQL no
Performance ✅ Cheap, reduces work early More expensive

[!TIP] 💡 Pro tip: If a condition does not need an aggregate function, it belongs in WHERE. Putting WHERE p.discontinued = 0 into HAVING would still give the right answer but force the engine to group rows it was going to throw away. On large tables this is a serious waste.

26.4 💼 Real-world grouping recipes

-- 🏆 Top 5 customers by lifetime spend
-- 🟥 MSSQL
SELECT TOP 5
    c.full_name,
    c.country,
    COUNT(DISTINCT o.order_id)                                AS orders,
    ROUND(SUM(oi.unit_price*oi.quantity*(1-oi.discount)), 2)  AS lifetime_spend
FROM customers c
JOIN orders o       ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped')
GROUP BY c.customer_id, c.full_name, c.country
ORDER BY lifetime_spend DESC;
-- 🟦 MySQL: identical, with LIMIT
SELECT
    c.full_name,
    c.country,
    COUNT(DISTINCT o.order_id)                                AS orders,
    ROUND(SUM(oi.unit_price*oi.quantity*(1-oi.discount)), 2)  AS lifetime_spend
FROM customers c
JOIN orders o       ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped')
GROUP BY c.customer_id, c.full_name, c.country
ORDER BY lifetime_spend DESC
LIMIT 5;
-- 📦 Best-selling products by units and revenue
SELECT
    p.product_name,
    SUM(oi.quantity)                                          AS units_sold,
    ROUND(SUM(oi.unit_price*oi.quantity*(1-oi.discount)), 2)  AS revenue,
    COUNT(DISTINCT oi.order_id)                               AS appeared_in_orders
FROM products p
JOIN order_items oi ON oi.product_id = p.product_id
JOIN orders o       ON o.order_id = oi.order_id
WHERE o.status IN ('Delivered','Shipped')
GROUP BY p.product_id, p.product_name
ORDER BY revenue DESC;
-- 👔 Sales performance per employee
SELECT
    CONCAT(e.first_name, ' ', e.last_name)                    AS sales_rep,
    COUNT(DISTINCT o.order_id)                                AS orders_handled,
    ROUND(SUM(oi.unit_price*oi.quantity*(1-oi.discount)), 2)  AS revenue,
    ROUND(SUM(oi.unit_price*oi.quantity*(1-oi.discount))
          / COUNT(DISTINCT o.order_id), 2)                    AS avg_order_value
FROM employees e
JOIN orders o       ON o.employee_id = e.employee_id
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped')
GROUP BY e.employee_id, e.first_name, e.last_name
ORDER BY revenue DESC;
-- 🌍 Revenue by country, only countries worth reporting on
SELECT
    c.country,
    COUNT(DISTINCT c.customer_id)                             AS customers,
    COUNT(DISTINCT o.order_id)                                AS orders,
    ROUND(SUM(oi.unit_price*oi.quantity*(1-oi.discount)), 2)  AS revenue
FROM customers c
JOIN orders o       ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped')
GROUP BY c.country
HAVING SUM(oi.unit_price*oi.quantity*(1-oi.discount)) > 500
ORDER BY revenue DESC;
-- 🔁 Find duplicate emails (the classic data-quality query)
SELECT email, COUNT(*) AS occurrences
FROM customers
GROUP BY email
HAVING COUNT(*) > 1;

[!TIP] 💡 That last query is worth memorizing. GROUP BY x HAVING COUNT(*) > 1 is how you find duplicates of anything, in any table, in any database. You will use it hundreds of times.

[!IMPORTANT] 🎯 GROUP BY or a window function? They answer different questions, and picking wrong is the most common source of over-complicated SQL:

You want… Use
One row per group — “revenue per category” GROUP BY
Every row, plus its group’s figure — “each product and its category average” Window function (Ch 33)
A filter on the group total GROUP BY … HAVING
A rank, running total, or previous-row comparison Window function
To collapse 1,000,000 rows into 12 GROUP BY

If you find yourself joining a GROUP BY result back to the original table just to see the detail rows again, you wanted a window function.

26.5 🐛 The three GROUP BY mistakes

① Forgetting a column in GROUP BY

-- ❌ MSSQL: "Column 'customers.country' is invalid in the select list..."
SELECT full_name, country, COUNT(*) FROM customers GROUP BY full_name;

-- ✅ Every non-aggregated SELECT column must appear in GROUP BY
SELECT full_name, country, COUNT(*) FROM customers GROUP BY full_name, country;

② Counting the wrong thing after a join

-- ❌ Counts LINE ITEMS, not orders
SELECT c.full_name, COUNT(*) AS orders
FROM customers c
JOIN orders o       ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY c.full_name;

-- ✅ Counts orders
SELECT c.full_name, COUNT(DISTINCT o.order_id) AS orders
FROM customers c
JOIN orders o       ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY c.full_name;

③ Losing rows with zero matches

-- ❌ Customers who never ordered vanish entirely (INNER JOIN)
SELECT c.full_name, COUNT(o.order_id) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.full_name;

-- ✅ LEFT JOIN keeps them, showing 0
SELECT c.full_name, COUNT(o.order_id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.full_name
ORDER BY orders;

[!WARNING] ⚠️ Note it must be COUNT(o.order_id), not COUNT(*), in that last query. With a LEFT JOIN, a customer with no orders still produces one row (with NULLs), so COUNT(*) would return 1 instead of 0. COUNT(o.order_id) skips the NULL and correctly returns 0. This is one of the most valuable details in this entire chapter.

26.6 🧪 Try it yourself

  1. Count orders per status, sorted by count.
  2. Find every category whose average product price exceeds 300.
  3. List customers with more than 2 orders, showing their total spend.
  4. Find any duplicate product_name values.
  5. Show every customer including those with zero orders, correctly displaying 0.

🧭 In practice — GROUP BY and HAVING

How to use it. GROUP BY collapses rows into one row per distinct combination of the grouping columns; HAVING then filters those groups. Every column in the SELECT list must either appear in GROUP BY or sit inside an aggregate. Expected result: one row per category, per customer, per month — whatever you grouped by.

When to use it. Whenever the question is “per something”: revenue per month, orders per customer, average price per category.

Where to use it. Every report and dashboard you will ever write. Scenario: “which categories have at least 3 products, and what do they average?” — WHERE discontinued = 0 removes unwanted products first, GROUP BY category_id buckets them, and HAVING COUNT(*) >= 3 drops the small categories.

When not to use it. Do not put a non-aggregate filter in HAVING. WHERE discards rows before grouping, so the same condition in HAVING makes the engine group rows it is about to throw away — same answer, more work. Also be wary of MySQL’s historical tolerance for selecting ungrouped columns: with ONLY_FULL_GROUP_BY disabled it returns an arbitrary value rather than an error, which is a genuine correctness hazard, not a convenience.

Best practices. Remember the order: WHERE filters rows, GROUP BY buckets them, HAVING filters buckets, SELECT computes the output, ORDER BY sorts it. Grouping on a wide text column is much more expensive than grouping on its integer key — group by category_id and join to categories for the name. And check for join-caused row multiplication before trusting any grouped total.


27. ROLLUP, CUBE, and GROUPING SETS

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟡 Intermediate 20 min Add subtotals and grand totals · Build cross-tab summaries · Tell a subtotal row from real data

[!NOTE] 📌 In plain words: These give you subtotals and grand totals for free, in the same query — the thing every manager asks for and every beginner does with three separate queries stitched together.

🌍 Analogy: A shop receipt. You get a line per item, a subtotal per department, and a grand total at the bottom. ROLLUP produces exactly that shape.

27.1 📊 ROLLUP — hierarchical subtotals

-- ✅ Works in BOTH (syntax differs slightly)

-- 🟥 MSSQL
SELECT
    c.country,
    c.loyalty_tier,
    COUNT(*) AS customer_count
FROM customers c
GROUP BY ROLLUP (c.country, c.loyalty_tier)
ORDER BY c.country, c.loyalty_tier;
-- 🟦 MySQL
SELECT
    country,
    loyalty_tier,
    COUNT(*) AS customer_count
FROM customers
GROUP BY country, loyalty_tier WITH ROLLUP;

What comes back:

country loyalty_tier customer_count meaning
NULL NULL 12 grand total
Czechia NULL 1 subtotal for Czechia
Czechia Bronze 1 detail row
Denmark NULL 1 subtotal for Denmark
Denmark Bronze 1 detail row
Germany NULL 1 subtotal for Germany
Germany Bronze 1 detail row
… … …  
UK Silver 1 detail row

[!NOTE] 📌 ROLLUP works from right to left. It starts with the full detail (country, tier), then drops the last column to make a subtotal per country (country), then drops everything for one grand total ().

[!WARNING] ⚠️ Notice where the totals land. Because the subtotal rows carry NULL, and NULL sorts first in an ascending sort (Chapter 15), the grand total appears at the top and each country’s subtotal appears above its detail rows — not underneath, the way a spreadsheet would show it. To get the familiar receipt layout, sort by GROUPING() — it returns 1 on a total row (see 27.4):

-- 🟥 MSSQL: detail rows first, then subtotals, then the grand total
SELECT c.country, c.loyalty_tier, COUNT(*) AS customer_count
FROM customers c
GROUP BY ROLLUP (c.country, c.loyalty_tier)
ORDER BY GROUPING(c.country), c.country, GROUPING(c.loyalty_tier), c.loyalty_tier;

27.2 🎲 CUBE — every possible combination

-- 🟥 MSSQL only (MySQL has no CUBE)
SELECT
    c.country,
    c.loyalty_tier,
    COUNT(*) AS customer_count
FROM customers c
GROUP BY CUBE (c.country, c.loyalty_tier)
ORDER BY c.country, c.loyalty_tier;

CUBE gives you: per country+tier, per country, per tier, and the grand total. With n columns you get 2ⁿ combinations.

  ROLLUP CUBE
Combinations for (a, b) (a,b), (a), () (a,b), (a), (b), ()
Use for Things that nest: country → city; year → month Summaries where every combination of columns matters
MySQL support ✅ WITH ROLLUP ❌ Not supported

27.3 🎛️ GROUPING SETS — exactly the totals you want

-- 🟥 MSSQL only
SELECT
    c.country,
    c.loyalty_tier,
    COUNT(*) AS customer_count
FROM customers c
GROUP BY GROUPING SETS (
    (c.country, c.loyalty_tier),   -- detail
    (c.country),                   -- per country
    ()                             -- grand total
)
ORDER BY c.country, c.loyalty_tier;

[!TIP] 💡 GROUPING SETS is the most precise of the three. ROLLUP and CUBE are just shorthand for particular grouping sets. Use it when you want, say, totals by country and totals by tier but not the combination.

27.4 🏷️ Telling a subtotal NULL from a real NULL

A genuine problem: if city can be NULL in your data, how do you know whether a NULL in the result is a real NULL or a ROLLUP subtotal marker?

-- 🟥 MSSQL: GROUPING() returns 1 for a subtotal row
SELECT
    CASE WHEN GROUPING(c.country) = 1 THEN 'ALL COUNTRIES' ELSE c.country END      AS country,
    CASE WHEN GROUPING(c.loyalty_tier) = 1 THEN 'All tiers' ELSE c.loyalty_tier END AS tier,
    COUNT(*) AS customer_count
FROM customers c
GROUP BY ROLLUP (c.country, c.loyalty_tier);
-- 🟦 MySQL: GROUPING() exists from 8.0
SELECT
    IF(GROUPING(country) = 1, 'ALL COUNTRIES', country) AS country_label,   -- not "AS country": that makes GROUP BY country ambiguous
    IF(GROUPING(loyalty_tier) = 1, 'All tiers', loyalty_tier) AS tier_label,
    COUNT(*) AS customer_count
FROM customers
GROUP BY country, loyalty_tier WITH ROLLUP;

27.5 💼 A real management report

-- ✅ Monthly revenue with a yearly total — the classic finance request
-- 🟥 MSSQL
SELECT
    CASE WHEN GROUPING(YEAR(o.order_date))  = 1 THEN 'ALL YEARS'
         ELSE CAST(YEAR(o.order_date) AS VARCHAR(4)) END      AS yr,
    CASE WHEN GROUPING(MONTH(o.order_date)) = 1 THEN 'Full year'
         ELSE CAST(MONTH(o.order_date) AS VARCHAR(2)) END     AS mth,
    COUNT(DISTINCT o.order_id)                                AS orders,
    ROUND(SUM(oi.unit_price*oi.quantity*(1-oi.discount)), 2)  AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped')
GROUP BY ROLLUP (YEAR(o.order_date), MONTH(o.order_date))
ORDER BY yr, mth;

[!WARNING] ⚠️ WITH ROLLUP in MySQL cannot be combined with ORDER BY in older versions, and the subtotal rows always sort with their NULLs. If ordering matters, wrap the whole query in a subquery inside FROM (a derived table, Chapter 30) and sort outside it.

27.6 🧪 Try it yourself

  1. Produce a customer count by country with a grand total.
  2. In MSSQL, use CUBE on (country, loyalty_tier) and count how many rows come back. Explain the number.
  3. Build a revenue report grouped by category with a grand total, labelling the total row clearly.
  4. Use GROUPING SETS (MSSQL) to get totals by country and by tier, but not the combination.

🧭 In practice — ROLLUP, CUBE, and GROUPING SETS

How to use it. Add WITH ROLLUP (both engines) or GROUPING SETS/CUBE (SQL Server) to a GROUP BY to get subtotals and a grand total in the same result set. Tell a real NULL apart from a subtotal placeholder with the GROUPING() function. Expected result: detail rows and their subtotals in one pass, instead of several queries stitched together.

When to use it. When a report needs totals at more than one level — per product and per category and overall.

Where to use it. Financial and management reporting. Scenario: a sales report showing each category, a subtotal per region, and a grand total. ROLLUP produces all three levels in one query; the alternative is three queries plus UNION ALL, which reads the table three times and can disagree with itself if data changes between reads.

When not to use it. Skip these when a reporting tool, spreadsheet, or BI layer is already producing subtotals — duplicating that work in SQL makes both harder to change. CUBE in particular generates every possible combination of grouping columns, which grows exponentially: four columns give sixteen groupings, most of which nobody asked for.

Best practices. Always use GROUPING() to label subtotal rows rather than testing for NULL — otherwise a genuine NULL in a grouping column is indistinguishable from a subtotal marker, and your report quietly shows a category called “Total”. Order the results carefully, because subtotal rows sort unintuitively by default. ROLLUP is the portable one of the three; CUBE and GROUPING SETS are SQL Server here.


✅ Checkpoint — after Chapter 27 · you can query one table

[!IMPORTANT] This is the largest single milestone in the guide. Everything after it combines tables; everything before it is the foundation that makes those combinations meaningful.

🗣️ Teach it back

What is it? Why does it matter? How does it work? Can I give an example? — for each of:

  • A table, a row, a column, and a primary key (Ch 1)
  • A foreign key, and what “relational” actually means (Ch 1, 9)
  • The logical query processing order (Ch 5)
  • Constraints — and why they belong in the database (Ch 9)
  • NULL and three-valued logic (Ch 15)
  • Aggregates, GROUP BY, and HAVING (Ch 25–26)
🧪 Self-check questions
  1. Why can you use a column alias in ORDER BY but not in WHERE?
  2. A colleague says “we validate everything in the application, so we do not need constraints.” What is the counter-argument, in one sentence?
  3. WHERE status <> 'shipped' returns fewer rows than you expected. What is the most likely reason?
  4. What is the difference between WHERE and HAVING, and why does putting a non-aggregate filter in HAVING cost you?
  5. You are about to run DELETE FROM orders WHERE status = 'cancelled'. What do you do first?
  6. Why is DECIMAL(10,2) the right type for money and FLOAT the wrong one?
📝 Sample answers
  1. Because WHERE runs at step 2 and SELECT at step 5. When WHERE is evaluated the alias does not exist yet; by the time ORDER BY runs at step 7 it does. The two fixes are to repeat the expression, or to compute it first in a subquery or CTE. See §5.3.

  2. The database is the only place every route passes through. The website, a phone-order screen, a nightly import, and a person running SQL by hand all go through the constraint; only one of them goes through the application. The application should still validate for a friendly message, but the constraint is what makes the bad row impossible rather than merely unlikely.

  3. Rows where status is NULL. NULL <> 'shipped' evaluates to unknown, not true, so those rows are silently dropped. Write WHERE status <> 'shipped' OR status IS NULL, or make the column NOT NULL with a default. See Chapter 15.

  4. WHERE filters rows before grouping; HAVING filters groups after. A non-aggregate filter in HAVING gives the same answer but makes the engine group rows it is about to discard — you pay for the grouping work twice over.

  5. Run SELECT COUNT(*) with the identical WHERE clause, and check the number is what you expect. Then wrap the DELETE in an explicit transaction so a wrong count can be rolled back. This habit is the difference between a routine task and an incident.

  6. FLOAT cannot represent most decimal fractions exactly. Values drift by tiny amounts, so a column of prices does not add up to what a human calculates, and the error compounds across a month of transactions. DECIMAL stores the exact value. See Chapter 6.

🎯 Give a simple example

Using only ShopDB and what you have learned so far, answer out loud: “how would I find the three categories with the highest average product price, ignoring discontinued products?” Name the clauses you need and the order the database will run them in.


Part index Prerequisites Previous Next Full course