Module 3 · SQL: Getting Data Out of Databases · Lesson 9 of 51

Summaries: GROUP BY, HAVING and CASE

COUNT, SUM, AVG, MIN and MAX, grouping rows, filtering groups with HAVING, labelling with CASE WHEN, and the order SQL really runs in.

In this lesson · about 40 minutes

  • Summarise with aggregate functions and GROUP BY
  • Filter groups with HAVING and rows with WHERE, and know the difference
  • Create categories with CASE WHEN

Aggregates

COUNT(*) counts rows; COUNT(column) counts non-missing values; COUNT(DISTINCT column) counts unique values. SUM, AVG, MIN and MAX do what they say. ROUND(AVG(total), 2) tidies the result.

SELECT branch,
       COUNT(*)              AS n_orders,
       ROUND(SUM(total), 2)  AS revenue,
       ROUND(AVG(total), 2)  AS avg_order
FROM orders
GROUP BY branch
ORDER BY revenue DESC;

Rule: every column in SELECT must either be in GROUP BY or be inside an aggregate. You can group by several columns (GROUP BY branch, category) for one row per combination.

WHERE vs HAVING

WHERE filters rows before grouping; HAVING filters groups after. "Branches with more than 1,000 orders" needs HAVING COUNT(*) > 1000, because the count doesn't exist until the groups are made.

The order SQL actually runs in

You write SELECT first, but the database works in this order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. That's why you can't use a SELECT alias in WHERE, but you can in ORDER BY.

CASE WHEN: if-then inside SQL

SELECT CASE WHEN hour < 11 THEN 'Morning'
            WHEN hour < 15 THEN 'Lunch'
            ELSE 'Afternoon' END AS daypart,
       COUNT(*) AS n_orders
FROM orders
GROUP BY daypart;

A handy trick: AVG(CASE WHEN payment = 'App' THEN 1 ELSE 0 END) is the share of orders paid by app.

Missing values

Aggregates skip NULLs, so AVG(qty) averages only the known quantities. COALESCE(qty, 1) replaces a NULL with 1. Decide deliberately; don't let the default decide for you.

Revenue by branch and daypart

Exercise

Category scorecard

For each category, return category, the number of orders as n_orders, and the average order total rounded to 2 decimals as avg_total. Keep only categories with an average above 5, and sort by avg_total from highest to lowest.

Code that runs before yours
import sqlite3
import pandas as pd
con = sqlite3.connect(":memory:")
pd.read_csv("kc_orders.csv").to_sql("orders", con, index=False)
q = lambda sql: pd.read_sql_query(sql, con)

Exercise

App share by branch

For each branch, return branch and app_share: the share of its orders paid with 'App', rounded to 3 decimals. Sort by app_share, highest first. Use the AVG(CASE WHEN …) trick.

Code that runs before yours
import sqlite3
import pandas as pd
con = sqlite3.connect(":memory:")
pd.read_csv("kc_orders.csv").to_sql("orders", con, index=False)
q = lambda sql: pd.read_sql_query(sql, con)

Check your understanding0 of 4 correct

Question 1

1.'Branches with over 1,000 orders' needs…

Question 2

2.Which runs first?

Question 3

3.COUNT(qty) vs COUNT(*) when qty has NULLs?

Question 4

4.AVG(CASE WHEN converted = 1 THEN 1.0 ELSE 0 END) gives…

Quiz score: 0 of 4

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.