Skip to content

30. SQL for data analysis — Exercises

These exercises practice every idea of the SQL lesson. They query the course database data/shop.db (tables stores, products, customers and orders; see the data dictionary) with sqlite3, and the CSV and Parquet files with DuckDB.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block below into a script, then the starter code under it. Replace each to-do comment with your code.
  3. Run the script. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert statements that check the result. Add the same checks to your own code.

Every exercise starts with this block. It opens data/shop.db read-only, so no exercise can change the course data, and it defines the show() helper from the lesson.

import sqlite3
import duckdb
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
con = sqlite3.connect("file:data/shop.db?mode=ro", uri=True)
def show(
sql: str,
params: tuple | dict = (),
db: sqlite3.Connection | None = None,
max_rows: int = 15,
) -> None:
"""Run a query and print the rows as an aligned text table."""
cur = (db or con).execute(sql, params)
names = [column[0] for column in cur.description]
rows = cur.fetchall()
cells = [["NULL" if v is None else str(v) for v in row] for row in rows[:max_rows]]
widths = [max(map(len, column)) for column in zip(names, *cells)]
first = rows[0] if rows else [None] * len(names)
right = [isinstance(v, int | float) for v in first]
def line(values: list[str]) -> str:
parts = zip(values, widths, right)
return " ".join(v.rjust(w) if r else v.ljust(w) for v, w, r in parts).rstrip()
print(line(names))
for row in cells:
print(line(row))
if len(rows) > max_rows:
print(f"... {len(rows) - max_rows} more rows")
Warm-up

The West regional manager wants her stores, largest first. Select store_id, city, size_sqm and opened of the stores in the West region, sorted by floor area from largest to smallest.

Expected output
store_id city size_sqm opened
S10 Seattle 2480 2010-06-19
S11 San Francisco 1890 2014-07-26
S12 Denver 1350 2023-06-15
Starter
show("""
SELECT store_id, city, size_sqm, opened
FROM stores
-- TODO: keep only the West region
-- TODO: sort by size_sqm, largest first
""")
Hint 1

Text values go in single quotes: WHERE region = 'West'.

Hint 2

ORDER BY size_sqm DESC sorts from largest to smallest. ORDER BY comes after WHERE.

Solution
west_sql = """
SELECT store_id, city, size_sqm, opened
FROM stores
WHERE region = 'West'
ORDER BY size_sqm DESC
"""
show(west_sql)
rows = con.execute(west_sql).fetchall()
assert [row[0] for row in rows] == ["S10", "S11", "S12"]
assert rows[0][2] > rows[1][2] > rows[2][2]
Output
store_id city size_sqm opened
S10 Seattle 2480 2010-06-19
S11 San Francisco 1890 2014-07-26
S12 Denver 1350 2023-06-15

How it works:

  1. FROM stores names the table. WHERE region = 'West' keeps the three West stores.
  2. ORDER BY size_sqm DESC sorts by floor area, largest first.
  3. The asserts run the same SQL with fetchall() and check the ids and the order.

Alternative: in DuckDB, query the CSV file directly: duckdb.sql("SELECT ... FROM 'data/stores.csv' WHERE region = 'West' ORDER BY size_sqm DESC"). DuckDB also reads opened as a real DATE.

M30-W02 · The five most expensive products

Section titled “M30-W02 · The five most expensive products”
Warm-up

List the five products with the highest unit_price: product_id, product, category and unit_price.

Expected output
product_id product category unit_price
P003 55-inch 4K Smart TV Electronics 1299.0
P004 14-inch Ultrabook Laptop Electronics 1149.0
P006 Espresso Machine Home 349.0
P007 Robot Vacuum Home 299.99
P018 Adjustable Dumbbells Sports 279.0
Starter
show("""
SELECT product_id, product, category, unit_price
FROM products
-- TODO: sort and keep five rows
""")
Hint 1

Sort first, then cut: ORDER BY ... DESC and then LIMIT 5.

Solution
top5_sql = """
SELECT product_id, product, category, unit_price
FROM products
ORDER BY unit_price DESC
LIMIT 5
"""
show(top5_sql)
rows = con.execute(top5_sql).fetchall()
assert len(rows) == 5
assert rows[0][0] == "P003"
assert all(a[3] >= b[3] for a, b in zip(rows, rows[1:]))
Output
product_id product category unit_price
P003 55-inch 4K Smart TV Electronics 1299.0
P004 14-inch Ultrabook Laptop Electronics 1149.0
P006 Espresso Machine Home 349.0
P007 Robot Vacuum Home 299.99
P018 Adjustable Dumbbells Sports 279.0

How it works:

  1. ORDER BY unit_price DESC puts the most expensive product first.
  2. LIMIT 5 keeps the first five rows of the sorted result. LIMIT always runs last.
  3. The last assert checks that every price is at least as high as the next one.

Alternative: pandas: pd.read_sql_query("SELECT * FROM products", con).nlargest(5, "unit_price"). It loads all 30 rows first, which is fine for a small table but not for a big one.

M30-W03 · Predict the output: NULL in SQL

Section titled “M30-W03 · Predict the output: NULL in SQL”
Warm-up

Predict the output: ten customers in customers have NULL in total_charges. Write down what each line prints. Then run the code and compare.

Acceptance criteria:

  • Write your prediction for every value before you run the code.
  • Run the code. Your prediction matches the Output in the solution.
  • For each wrong value, you can name the NULL rule that explains it.
Starter
show("""
SELECT COUNT(*) AS all_rows,
COUNT(total_charges) AS known,
SUM(total_charges IS NULL) AS missing,
COUNT(*) FILTER (WHERE total_charges = NULL) AS eq_null,
COALESCE(NULL, NULL, 'n/a') AS first_known
FROM customers
""")
print(con.execute("SELECT NULL + 1, NULL OR 1, NULL AND 0, NULL = NULL").fetchone())
# TODO: write your prediction for each value before you run it
Hint 1

COUNT(col) skips NULLs; COUNT(*) counts rows. IS NULL is 1 or 0 in SQLite.

Hint 2

A comparison with NULL is unknown (NULL), and a filter keeps only true rows. NULL OR 1 is true whatever the unknown value is; NULL AND 0 is false whatever it is.

Solution
show("""
SELECT COUNT(*) AS all_rows,
COUNT(total_charges) AS known,
SUM(total_charges IS NULL) AS missing,
COUNT(*) FILTER (WHERE total_charges = NULL) AS eq_null,
COALESCE(NULL, NULL, 'n/a') AS first_known
FROM customers
""")
values = con.execute("SELECT NULL + 1, NULL OR 1, NULL AND 0, NULL = NULL").fetchone()
print(values)
assert values == (None, 1, 0, None)
Output
all_rows known missing eq_null first_known
5000 4990 10 0 n/a
(None, 1, 0, None)

How it works:

  1. COUNT(*) counts all 5,000 rows. COUNT(total_charges) skips the 10 NULLs.
  2. total_charges IS NULL is 1 for the 10 missing values, so the SUM is 10.
  3. total_charges = NULL is never true, so the filtered count is 0.
  4. COALESCE returns its first argument that is not NULL: 'n/a'.
  5. NULL + 1 is NULL: unknown plus 1 is unknown. NULL OR 1 is 1, because one true side is enough. NULL AND 0 is 0, because one false side is enough. NULL = NULL is NULL. sqlite3 returns NULL as None.

Alternative: in DuckDB, SELECT NULL + 1, NULL OR true, NULL AND false, NULL = NULL returns (None, True, False, None). The logic is the same; DuckDB shows True and False because it has a real Boolean type.

Warm-up

How do the two sales channels compare? For each channel in orders, show the number of lines, the total revenue and the average line revenue, both rounded to 2 decimals, largest revenue first.

Expected output
channel lines revenue avg_line
store 11733 2077057.36 177.03
online 8495 1519466.47 178.87
Starter
show("""
SELECT channel,
-- TODO: number of lines, total revenue, average revenue
FROM orders
-- TODO: one group per channel, largest revenue first
""")
Hint 1

COUNT(*), SUM(revenue) and AVG(revenue) are the three aggregates. Wrap the money values in ROUND(..., 2).

Hint 2

GROUP BY channel makes one row per channel. ORDER BY revenue DESC can use the alias.

Solution
channel_sql = """
SELECT channel,
COUNT(*) AS lines,
ROUND(SUM(revenue), 2) AS revenue,
ROUND(AVG(revenue), 2) AS avg_line
FROM orders
GROUP BY channel
ORDER BY revenue DESC
"""
show(channel_sql)
rows = con.execute(channel_sql).fetchall()
assert sum(row[1] for row in rows) == 20228
assert abs(sum(row[2] for row in rows) - 3596523.83) < 0.05
Output
channel lines revenue avg_line
store 11733 2077057.36 177.03
online 8495 1519466.47 178.87

How it works:

  1. GROUP BY channel splits the 20,228 lines into two groups.
  2. Each aggregate runs once per group. AVG(revenue) equals SUM(revenue) / COUNT(*).
  3. The asserts check that the groups add up to the whole table: every line is in exactly one group.

Alternative: pandas on the CSV: pd.read_csv("data/sales.csv").groupby("channel")["revenue"].agg(["size", "sum", "mean"]).

M30-W05 · Fix the bug: whole-number percentages

Section titled “M30-W05 · Fix the bug: whole-number percentages”
Warm-up

Fix the bug: this query should show the churn rate per contract type with one decimal, but every rate is a whole number.

show("""
SELECT contract, SUM(churned) * 100 / COUNT(*) AS churn_pct
FROM customers
GROUP BY contract
ORDER BY churn_pct DESC
""")
Output
contract churn_pct
month-to-month 29
one-year 8
two-year 3

Change the query so that it prints:

Expected output
contract churn_pct
month-to-month 29.6
one-year 8.8
two-year 3.2
Starter
show("""
SELECT contract, SUM(churned) * 100 / COUNT(*) AS churn_pct -- TODO: fix
FROM customers
GROUP BY contract
ORDER BY churn_pct DESC
""")
Hint 1

All three operands are integers. What does SQLite do with 293 / 990?

Hint 2

Make one operand a float, 100.0, and round with ROUND(..., 1).

Solution
churn_sql = """
SELECT contract, ROUND(100.0 * SUM(churned) / COUNT(*), 1) AS churn_pct
FROM customers
GROUP BY contract
ORDER BY churn_pct DESC
"""
show(churn_sql)
rates = dict(con.execute(churn_sql).fetchall())
assert rates == {"month-to-month": 29.6, "one-year": 8.8, "two-year": 3.2}
Output
contract churn_pct
month-to-month 29.6
one-year 8.8
two-year 3.2

How it works:

  1. SUM(churned) * 100 is an integer and COUNT(*) is an integer, so SQLite used integer division and dropped the decimals.
  2. 100.0 is a float. 100.0 * SUM(churned) is a float, so the division keeps its decimals.
  3. ROUND(..., 1) keeps one decimal. dict(rows) turns the two-column rows into a dict for the assert.

Alternative: ROUND(100 * AVG(churned), 1). AVG always returns a float, and the average of a 0/1 column is the rate. In DuckDB, the original query is already correct, because / never truncates there.

M30-W06 · Fix the bug: an aggregate in WHERE

Section titled “M30-W06 · Fix the bug: an aggregate in WHERE”
Warm-up

Fix the bug: this query should list the stores with more than 2,000 order lines, but it raises an error.

show("""
SELECT store_id, COUNT(*) AS lines
FROM orders
WHERE COUNT(*) > 2000
GROUP BY store_id
""")
Output
sqlite3.OperationalError: misuse of aggregate: COUNT()

Fix it, and sort the stores by their number of lines, largest first:

Expected output
store_id lines
S07 2541
S01 2220
S04 2199
S10 2190
Starter
show("""
SELECT store_id, COUNT(*) AS lines
FROM orders
WHERE COUNT(*) > 2000 -- TODO: this condition is in the wrong clause
GROUP BY store_id
-- TODO: sort by lines, largest first
""")
Hint 1

WHERE runs before GROUP BY. At that point, there are no groups to count.

Hint 2

HAVING filters groups after the aggregation. It comes after GROUP BY and before ORDER BY.

Solution
busy_sql = """
SELECT store_id, COUNT(*) AS lines
FROM orders
GROUP BY store_id
HAVING COUNT(*) > 2000
ORDER BY lines DESC
"""
show(busy_sql)
rows = con.execute(busy_sql).fetchall()
assert [row[0] for row in rows] == ["S07", "S01", "S04", "S10"]
assert all(row[1] > 2000 for row in rows)
Output
store_id lines
S07 2541
S01 2220
S04 2199
S10 2190

How it works:

  1. The logical order is FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY. An aggregate needs groups, so it cannot appear in WHERE.
  2. HAVING COUNT(*) > 2000 keeps the groups whose count is above 2,000.
  3. These are the four largest stores. Sales volume grows with floor area in this data.

Alternative: compute the counts in a CTE and filter in the outer query with WHERE lines > 2000. That is longer, but useful when several later steps need the counts.

Warm-up

The catalog team uses three price bands: budget (below 30 USD), mid (30 to below 150 USD) and premium (150 USD and more). Count the products and show the cheapest and the dearest price per band, in band order from budget to premium.

Expected output
band products lowest highest
budget 9 14.99 29.99
mid 12 32.0 129.99
premium 9 189.0 1299.0
Starter
show("""
SELECT CASE
-- TODO: three bands
END AS band,
COUNT(*) AS products
-- TODO: lowest and highest price
FROM products
GROUP BY band
-- TODO: budget, mid, premium order
""")
Hint 1

CASE WHEN unit_price < 30 THEN 'budget' WHEN unit_price < 150 THEN 'mid' ELSE 'premium' END. The branches run in order, so the second one only sees prices of 30 and more.

Hint 2

Sorting by the band name gives alphabetical order (budget, mid, premium happens to be alphabetical, but do not rely on that). ORDER BY MIN(unit_price) sorts by the real order.

Solution
band_sql = """
SELECT CASE
WHEN unit_price < 30 THEN 'budget'
WHEN unit_price < 150 THEN 'mid'
ELSE 'premium'
END AS band,
COUNT(*) AS products,
MIN(unit_price) AS lowest,
MAX(unit_price) AS highest
FROM products
GROUP BY band
ORDER BY MIN(unit_price)
"""
show(band_sql)
rows = con.execute(band_sql).fetchall()
assert [row[0] for row in rows] == ["budget", "mid", "premium"]
assert sum(row[1] for row in rows) == 30
Output
band products lowest highest
budget 9 14.99 29.99
mid 12 32.0 129.99
premium 9 189.0 1299.0

How it works:

  1. The CASE expression gives each product one band. The first true WHEN wins.
  2. GROUP BY band groups by the new column. SQLite allows the alias in GROUP BY.
  3. ORDER BY MIN(unit_price) puts the bands in price order, whatever their names.

Alternative: pandas pd.cut(products["unit_price"], bins=[0, 30, 150, float("inf")], right=False, labels=["budget", "mid", "premium"]) makes the same bands; right=False makes each band include its lower edge, like < in the CASE.

M30-W08 · A safe lookup with a placeholder

Section titled “M30-W08 · A safe lookup with a placeholder”
Warm-up

Write a function customer_plan(customer_id) that returns the plan of one customer, or None if the id does not exist. Use a ? placeholder. Test it with C00042, with C99999 and with the attack string x' OR '1'='1.

Expected output
C00042 -> standard
C99999 -> None
x' OR '1'='1 -> None
Starter
def customer_plan(customer_id: str) -> str | None:
# TODO: run a parameterized query and fetch one row
# TODO: return None when there is no row
...
for cid in ["C00042", "C99999", "x' OR '1'='1"]:
print(cid, "->", customer_plan(cid))
Hint 1

con.execute("SELECT plan FROM customers WHERE customer_id = ?", (customer_id,)). The comma makes a one-element tuple.

Hint 2

fetchone() returns a tuple such as ('basic',), or None when the query found nothing.

Solution
def customer_plan(customer_id: str) -> str | None:
row = con.execute(
"SELECT plan FROM customers WHERE customer_id = ?", (customer_id,)
).fetchone()
return None if row is None else row[0]
for cid in ["C00042", "C99999", "x' OR '1'='1"]:
print(cid, "->", customer_plan(cid))
assert customer_plan("C99999") is None
assert customer_plan("x' OR '1'='1") is None
Output
C00042 -> standard
C99999 -> None
x' OR '1'='1 -> None

How it works:

  1. The ? marks where the value goes. The value travels separately from the SQL text.
  2. The engine compares customer_id with the whole attack string as plain text. No customer has that id, so the result is None.
  3. fetchone() returns None at the end of the result, which the function passes on.

Alternative: a named placeholder with a dict: con.execute("SELECT plan FROM customers WHERE customer_id = :cid", {"cid": customer_id}). Named placeholders read better when a query has many values.

Warm-up

Without loading anything into pandas, use DuckDB to compute the number of products and the average unit_price (2 decimals) per category, straight from data/products.csv. Print the result with .show(max_width=100), highest average first.

Expected output
┌─────────────┬──────────┬───────────┐
│ category │ products │ avg_price │
│ varchar │ int64 │ double │
├─────────────┼──────────┼───────────┤
│ Electronics │ 5 │ 595.4 │
│ Home │ 5 │ 207.59 │
│ Sports │ 5 │ 146.79 │
│ Clothing │ 5 │ 60.69 │
│ Beauty │ 5 │ 30.89 │
│ Books │ 5 │ 24.29 │
└─────────────┴──────────┴───────────┘
Starter
rel = duckdb.sql("""
SELECT category
-- TODO: count and average price
FROM 'data/products.csv'
-- TODO: group and sort
""")
rel.show(max_width=100)
Hint 1

The file path in single quotes takes the place of a table name.

Hint 2

COUNT(*) AS products, ROUND(AVG(unit_price), 2) AS avg_price, then GROUP BY category ORDER BY avg_price DESC.

Solution
rel = duckdb.sql("""
SELECT category,
COUNT(*) AS products,
ROUND(AVG(unit_price), 2) AS avg_price
FROM 'data/products.csv'
GROUP BY category
ORDER BY avg_price DESC
""")
rel.show(max_width=100)
rows = rel.fetchall()
assert len(rows) == 6
assert rows[0][0] == "Electronics"
assert all(row[1] == 5 for row in rows)
Output
┌─────────────┬──────────┬───────────┐
│ category │ products │ avg_price │
│ varchar │ int64 │ double │
├─────────────┼──────────┼───────────┤
│ Electronics │ 5 │ 595.4 │
│ Home │ 5 │ 207.59 │
│ Sports │ 5 │ 146.79 │
│ Clothing │ 5 │ 60.69 │
│ Beauty │ 5 │ 30.89 │
│ Books │ 5 │ 24.29 │
└─────────────┴──────────┴───────────┘

How it works:

  1. DuckDB reads the CSV file, detects the header and the column types, and runs the query on it.
  2. .show(max_width=100) prints a box with the column names and types.
  3. .fetchall() runs the relation again and returns tuples for the asserts. Every category has 5 products.

Alternative: .df() returns the same result as a pandas DataFrame, for plotting or further work.

M30-C01 · Revenue per region: SQL and pandas agree

Section titled “M30-C01 · Revenue per region: SQL and pandas agree”
Core

orders has no region column. Join it to stores and compute the lines and revenue per region, largest first. Then compute the same totals in pandas from data/sales.csv, which has a region column, and assert that both tools agree to the cent.

Expected output
region lines revenue
East 5396 993683.72
South 5144 891766.07
North 4966 888229.47
West 4722 822844.57
largest difference: 0.0
Starter
region_sql = """
SELECT s.region, COUNT(*) AS lines, ROUND(SUM(o.revenue), 2) AS revenue
FROM orders AS o
-- TODO: join stores
-- TODO: group and sort
"""
show(region_sql)
sales = pd.read_csv("data/sales.csv")
# TODO: the same totals in pandas, then compare
Hint 1

JOIN stores AS s ON s.store_id = o.store_id. Each line matches exactly one store, so no fan-out.

Hint 2

In pandas: sales.groupby("region")["revenue"].sum().round(2). Read the SQL result into a dict with dict(con.execute(...).fetchall()) after selecting only region and revenue, or use pd.read_sql_query.

Solution
region_sql = """
SELECT s.region, COUNT(*) AS lines, ROUND(SUM(o.revenue), 2) AS revenue
FROM orders AS o
JOIN stores AS s ON s.store_id = o.store_id
GROUP BY s.region
ORDER BY revenue DESC
"""
show(region_sql)
sql_totals = pd.read_sql_query(region_sql, con).set_index("region")["revenue"]
sales = pd.read_csv("data/sales.csv")
pandas_totals = sales.groupby("region")["revenue"].sum().round(2)
difference = (sql_totals - pandas_totals).abs().max()
print("largest difference:", round(difference, 2))
assert difference < 0.005
Output
region lines revenue
East 5396 993683.72
South 5144 891766.07
North 4966 888229.47
West 4722 822844.57
largest difference: 0.0

How it works:

  1. The join adds s.region to every order line. GROUP BY s.region makes four groups.
  2. pd.read_sql_query returns the SQL result as a DataFrame. set_index("region")["revenue"] turns it into a Series keyed by region.
  3. Subtracting two Series aligns them by index (region), whatever their row order. The largest absolute difference is 0.

Alternative: DuckDB can run the pandas side in SQL too: duckdb.sql("SELECT region, ROUND(SUM(revenue), 2) FROM sales GROUP BY region").df() reads the DataFrame sales by its name.

M30-C02 · Online share per category with conditional aggregation

Section titled “M30-C02 · Online share per category with conditional aggregation”
Core

For each product category, show the online revenue, the store revenue and the online share of revenue in percent (1 decimal), in one query without a pivot. Sort by the online share, highest first.

Expected output
category online store online_pct
Beauty 63758.35 86659.41 42.4
Electronics 767072.48 1041035.69 42.4
Clothing 133153.32 181533.3 42.3
Home 284066.0 388228.61 42.3
Books 44644.66 62263.46 41.8
Sports 226771.66 317336.89 41.7
Starter
show("""
SELECT p.category,
-- TODO: online revenue, store revenue, online share
FROM orders AS o
JOIN products AS p ON p.product_id = o.product_id
GROUP BY p.category
ORDER BY online_pct DESC
""")
Hint 1

SUM(CASE WHEN o.channel = 'online' THEN o.revenue ELSE 0 END) adds only the online revenue.

Hint 2

The share is 100.0 * online / SUM(o.revenue). You cannot reuse the alias online inside the same SELECT, so repeat the CASE expression, or compute the totals in a CTE first.

Solution
share_sql = """
WITH totals AS (
SELECT p.category,
SUM(CASE WHEN o.channel = 'online' THEN o.revenue ELSE 0 END) AS online,
SUM(CASE WHEN o.channel = 'store' THEN o.revenue ELSE 0 END) AS store
FROM orders AS o
JOIN products AS p ON p.product_id = o.product_id
GROUP BY p.category
)
SELECT category,
ROUND(online, 2) AS online,
ROUND(store, 2) AS store,
ROUND(100.0 * online / (online + store), 1) AS online_pct
FROM totals
ORDER BY online_pct DESC
"""
show(share_sql)
result = pd.read_sql_query(share_sql, con)
assert len(result) == 6
assert result["online_pct"].between(0, 100).all()
assert abs((result["online"] + result["store"]).sum() - 3596523.83) < 0.05
Output
category online store online_pct
Beauty 63758.35 86659.41 42.4
Electronics 767072.48 1041035.69 42.4
Clothing 133153.32 181533.3 42.3
Home 284066.0 388228.61 42.3
Books 44644.66 62263.46 41.8
Sports 226771.66 317336.89 41.7

How it works:

  1. Each SUM(CASE ...) adds the revenue of one channel and 0 for the other lines. One pass over the table fills both columns.
  2. The CTE totals names the two sums, so the outer query can use them in the share formula.
  3. 100.0 keeps the division exact. The shares differ little between categories.

Alternative: SUM(o.revenue) FILTER (WHERE o.channel = 'online') is a shorter form of the CASE sum in SQLite and DuckDB. In pandas: sales.pivot_table(index="category", columns="channel", values="revenue", aggfunc="sum").

Core

A lapsed customer ordered in 2023 but not in 2024. Count the customers who ordered in 2023, split them into lapsed and active (ordered in both years), and show the churn rate and the average logins_last_30d of each group. Then interpret the result in one or two sentences.

Expected output
status customers churn_pct avg_logins
active 1524 9.4 11.8
lapsed 399 10.8 12.3
Starter
show("""
SELECT CASE
-- TODO: 'active' when an order in 2024 exists, else 'lapsed'
END AS status,
COUNT(*) AS customers,
ROUND(100.0 * AVG(c.churned), 1) AS churn_pct,
ROUND(AVG(c.logins_last_30d), 1) AS avg_logins
FROM customers AS c
WHERE EXISTS (
-- TODO: an order of this customer in 2023
)
GROUP BY status
""")
Hint 1

Two correlated subqueries do the work: one in WHERE (ordered in 2023) and one inside the CASE (ordered in 2024).

Hint 2

Use half-open date ranges: o.order_date >= '2023-01-01' AND o.order_date < '2024-01-01'.

Solution
lapsed_sql = """
SELECT CASE
WHEN EXISTS (SELECT 1 FROM orders AS o
WHERE o.customer_id = c.customer_id
AND o.order_date >= '2024-01-01')
THEN 'active' ELSE 'lapsed'
END AS status,
COUNT(*) AS customers,
ROUND(100.0 * AVG(c.churned), 1) AS churn_pct,
ROUND(AVG(c.logins_last_30d), 1) AS avg_logins
FROM customers AS c
WHERE EXISTS (SELECT 1 FROM orders AS o
WHERE o.customer_id = c.customer_id
AND o.order_date >= '2023-01-01'
AND o.order_date < '2024-01-01')
GROUP BY status
"""
show(lapsed_sql)
result = dict((row[0], row[1:]) for row in con.execute(lapsed_sql))
(n_2023,) = con.execute(
"SELECT COUNT(DISTINCT customer_id) FROM orders WHERE order_date < '2024-01-01'"
).fetchone()
assert result["active"][0] + result["lapsed"][0] == n_2023
Output
status customers churn_pct avg_logins
active 1524 9.4 11.8
lapsed 399 10.8 12.3

How it works:

  1. WHERE EXISTS (...) is a semi-join: it keeps each customer with at least one 2023 order, once.
  2. The CASE uses a second EXISTS to test for a 2024 order. No 2024 order means lapsed: an anti-join written as a CASE branch.
  3. The assert checks that the two groups together are exactly the 2023 buyers.

Interpretation: lapsed customers churn only a little more often than active ones (10.8% against 9.4%), and they log in just as often. In this data, stopping shop orders says little about leaving the subscription. Do not build a retention campaign on this signal alone; test it as one feature among many in a churn model (module 36). Both groups churn far less than the 19.3% average. They all bought in 2023, so they are older customers, and churn falls with tenure (see the tenure bands in the lesson).

Alternative: two CTEs, buyers_2023 and buyers_2024 (each SELECT DISTINCT customer_id ...), then buyers_2023 LEFT JOIN buyers_2024 and CASE WHEN b24.customer_id IS NULL THEN 'lapsed' ....

M30-C04 · Fix the bug: the left join that lost rows

Section titled “M30-C04 · Fix the bug: the left join that lost rows”
Core

Fix the bug: for each plan, the report should show all customers of that plan and how many of them placed at least one online order. The customers column is far too small.

show("""
SELECT c.plan,
COUNT(DISTINCT c.customer_id) AS customers,
COUNT(DISTINCT o.customer_id) AS online_buyers
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.channel = 'online'
GROUP BY c.plan
ORDER BY c.plan
""")
Output
plan customers online_buyers
basic 990 990
premium 525 525
standard 961 961

Fix the query so that it prints:

Expected output
plan customers online_buyers
basic 2028 990
premium 990 525
standard 1982 961
Starter
show("""
SELECT c.plan,
COUNT(DISTINCT c.customer_id) AS customers,
COUNT(DISTINCT o.customer_id) AS online_buyers
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.channel = 'online' -- TODO: this line removes customers
GROUP BY c.plan
ORDER BY c.plan
""")
Hint 1

A customer without an online order gets NULL in every o. column. What does WHERE NULL = 'online' do to that row?

Hint 2

Move the channel condition into the ON clause: ON o.customer_id = c.customer_id AND o.channel = 'online'.

Solution
plan_sql = """
SELECT c.plan,
COUNT(DISTINCT c.customer_id) AS customers,
COUNT(DISTINCT o.customer_id) AS online_buyers
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id AND o.channel = 'online'
GROUP BY c.plan
ORDER BY c.plan
"""
show(plan_sql)
rows = con.execute(plan_sql).fetchall()
assert sum(row[1] for row in rows) == 5000
assert all(row[2] < row[1] for row in rows)
Output
plan customers online_buyers
basic 2028 990
premium 990 525
standard 1982 961

How it works:

  1. In the bug, WHERE o.channel = 'online' runs after the join. Customers without an online order have o.channel NULL, the condition is unknown, and WHERE drops them. The left join behaves like an inner join.
  2. In the ON clause, the condition only decides which orders match. Unmatched customers stay, with NULLs.
  3. COUNT(DISTINCT o.customer_id) skips those NULLs, so it counts only the online buyers. All 5,000 customers are now in the report.

Alternative: join a filtered subquery: LEFT JOIN (SELECT DISTINCT customer_id FROM orders WHERE channel = 'online') AS o ON .... Then COUNT(o.customer_id) needs no DISTINCT, and the join has no fan-out.

M30-C05 · Predict the output: join row counts

Section titled “M30-C05 · Predict the output: join row counts”
Core

Predict the output: the two tables below have duplicate keys. Predict how many rows each join returns. Then run the code.

Acceptance criteria:

  • Write a prediction for each of the five counts before you run the code.
  • Run the code. Your predictions match the Output in the solution.
  • You can explain each count with “one row per matching pair”.
Starter
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE a (k INTEGER, label TEXT);
INSERT INTO a VALUES (1, 'a1'), (1, 'a2'), (2, 'a3'), (3, 'a4');
CREATE TABLE b (k INTEGER, label TEXT);
INSERT INTO b VALUES (1, 'b1'), (2, 'b2'), (2, 'b3'), (4, 'b4');
""")
for join in ["INNER", "LEFT", "RIGHT", "FULL"]:
sql = f"SELECT COUNT(*) FROM a {join} JOIN b ON a.k = b.k"
print(join, db.execute(sql).fetchone()[0])
print("CROSS", db.execute("SELECT COUNT(*) FROM a CROSS JOIN b").fetchone()[0])
# TODO: write your five predictions before you run it
Hint 1

For each key, multiply the number of rows with that key in a by the number in b.

Hint 2

Key 1: 2 × 1. Key 2: 1 × 2. Key 3 exists only in a, key 4 only in b. Each unmatched row adds one row to the joins that keep its side.

Solution
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE a (k INTEGER, label TEXT);
INSERT INTO a VALUES (1, 'a1'), (1, 'a2'), (2, 'a3'), (3, 'a4');
CREATE TABLE b (k INTEGER, label TEXT);
INSERT INTO b VALUES (1, 'b1'), (2, 'b2'), (2, 'b3'), (4, 'b4');
""")
counts = {}
for join in ["INNER", "LEFT", "RIGHT", "FULL"]:
sql = f"SELECT COUNT(*) FROM a {join} JOIN b ON a.k = b.k"
counts[join] = db.execute(sql).fetchone()[0]
print(join, counts[join])
counts["CROSS"] = db.execute("SELECT COUNT(*) FROM a CROSS JOIN b").fetchone()[0]
print("CROSS", counts["CROSS"])
db.close()
assert counts == {"INNER": 4, "LEFT": 5, "RIGHT": 5, "FULL": 6, "CROSS": 16}
Output
INNER 4
LEFT 5
RIGHT 5
FULL 6
CROSS 16

How it works:

  1. Inner: key 1 gives 2 × 1 = 2 pairs and key 2 gives 1 × 2 = 2 pairs: 4 rows. Duplicates multiply.
  2. Left: the 4 pairs plus a4 (key 3) with NULLs: 5. Right: the 4 pairs plus b4 (key 4): 5.
  3. Full: the 4 pairs plus both unmatched rows: 6. Cross: every pair, 4 × 4 = 16.
  4. The join type here is built with an f-string. That is safe, because the four words come from a fixed list in the code.

Alternative: check the same counts in pandas with a.merge(b, on="k", how=...) and how="cross". pandas follows the same pairing rule.

M30-C06 · The top customer of each region

Section titled “M30-C06 · The top customer of each region”
Core

The loyalty team wants the customer with the highest total revenue in each customer region (customers.region), with that revenue and the number of orders. Use a CTE and ROW_NUMBER().

Expected output
region customer_id revenue orders
East C01364 16023.65 44
North C01766 13341.26 36
West C01656 12785.14 24
South C00587 10590.79 32
Starter
show("""
WITH totals AS (
-- TODO: one row per customer: region, customer_id, revenue, orders
),
ranked AS (
-- TODO: number the customers inside each region by revenue
)
SELECT region, customer_id, revenue, orders
FROM ranked
WHERE pos = 1
ORDER BY revenue DESC
""")
Hint 1

totals: join orders to customers, GROUP BY c.region, c.customer_id, with ROUND(SUM(o.revenue), 2) and COUNT(DISTINCT o.order_id).

Hint 2

ranked: ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) AS pos.

Solution
top_customer_sql = """
WITH totals AS (
SELECT c.region, c.customer_id,
ROUND(SUM(o.revenue), 2) AS revenue,
COUNT(DISTINCT o.order_id) AS orders
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
GROUP BY c.region, c.customer_id
),
ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) AS pos
FROM totals
)
SELECT region, customer_id, revenue, orders
FROM ranked
WHERE pos = 1
ORDER BY revenue DESC
"""
show(top_customer_sql)
rows = con.execute(top_customer_sql).fetchall()
assert sorted(row[0] for row in rows) == ["East", "North", "South", "West"]
(best,) = con.execute(
"SELECT MAX(r) FROM (SELECT SUM(revenue) AS r FROM orders GROUP BY customer_id)"
).fetchone()
assert rows[0][2] == round(best, 2)
Output
region customer_id revenue orders
East C01364 16023.65 44
North C01766 13341.26 36
West C01656 12785.14 24
South C00587 10590.79 32

How it works:

  1. totals has one row per customer. COUNT(DISTINCT o.order_id) counts orders, not lines: an order can have up to 3 lines.
  2. ranked numbers the customers in each region, best first. SELECT * keeps all the columns of totals.
  3. The outer query keeps position 1 of each region. The last assert checks that the overall best customer is in the result.

Alternative: in DuckDB, QUALIFY ROW_NUMBER() OVER (...) = 1 replaces the ranked CTE, or arg_max(customer_id, revenue) with GROUP BY region returns the best customer per region directly.

M30-C07 · Year-to-date revenue and share of the year

Section titled “M30-C07 · Year-to-date revenue and share of the year”
Core

For each month of 2024 (as 01 … 12), show the revenue, the year-to-date revenue and the year-to-date share of the full-year revenue in percent (1 decimal).

Expected output
month revenue ytd ytd_pct
01 119596.89 119596.89 6.1
02 106320.41 225917.3 11.6
03 145567.22 371484.52 19.0
04 114917.5 486402.02 24.9
05 128716.36 615118.38 31.5
06 155854.41 770972.79 39.5
07 148989.14 919961.93 47.2
08 151791.33 1071753.26 54.9
09 141654.74 1213408.0 62.2
10 166147.92 1379555.92 70.7
11 268466.55 1648022.47 84.5
12 302911.77 1950934.24 100.0
Starter
show("""
WITH monthly AS (
-- TODO: month as '01'..'12' and revenue, 2024 only
)
SELECT month,
ROUND(revenue, 2) AS revenue
-- TODO: running total and share of the year
FROM monthly
ORDER BY month
""")
Hint 1

strftime('%m', order_date) gives the month number as text. Filter with order_date >= '2024-01-01' inside the CTE.

Hint 2

SUM(revenue) OVER (ORDER BY month) is the running total. SUM(revenue) OVER () (an empty window) is the total of all rows: the full year.

Solution
ytd_sql = """
WITH monthly AS (
SELECT strftime('%m', order_date) AS month, SUM(revenue) AS revenue
FROM orders
WHERE order_date >= '2024-01-01'
GROUP BY month
)
SELECT month,
ROUND(revenue, 2) AS revenue,
ROUND(SUM(revenue) OVER (ORDER BY month), 2) AS ytd,
ROUND(100.0 * SUM(revenue) OVER (ORDER BY month)
/ SUM(revenue) OVER (), 1) AS ytd_pct
FROM monthly
ORDER BY month
"""
show(ytd_sql)
rows = con.execute(ytd_sql).fetchall()
assert len(rows) == 12
assert rows[-1][3] == 100.0
assert abs(rows[-1][2] - 1950934.24) < 0.01
Output
month revenue ytd ytd_pct
01 119596.89 119596.89 6.1
02 106320.41 225917.3 11.6
03 145567.22 371484.52 19.0
04 114917.5 486402.02 24.9
05 128716.36 615118.38 31.5
06 155854.41 770972.79 39.5
07 148989.14 919961.93 47.2
08 151791.33 1071753.26 54.9
09 141654.74 1213408.0 62.2
10 166147.92 1379555.92 70.7
11 268466.55 1648022.47 84.5
12 302911.77 1950934.24 100.0

How it works:

  1. The CTE has one row per month of 2024.
  2. SUM(revenue) OVER (ORDER BY month) adds all months up to the current one. Months are unique, so the default frame has no ties.
  3. SUM(revenue) OVER () has no ORDER BY and no partition: every row sees all 12 months. Dividing gives the share. December reaches 100%. The last two months add almost 30% of the year.

Alternative: pandas: monthly["revenue"].cumsum() / monthly["revenue"].sum() * 100.

M30-C08 · Month-over-month orders per channel

Section titled “M30-C08 · Month-over-month orders per channel”
Core

For each channel, show the number of orders (distinct order_id) in each month of the last quarter of 2024 and the change from the previous month. The October change must compare with September, so compute the lag before you filter.

Expected output
channel month orders change
online 2024-10 317 46
online 2024-11 554 237
online 2024-12 628 74
store 2024-10 358 13
store 2024-11 464 106
store 2024-12 609 145
Starter
show("""
WITH monthly AS (
-- TODO: channel, month, orders
),
lagged AS (
-- TODO: previous month's orders, separately per channel
)
SELECT channel, month, orders, orders - prev_orders AS change
FROM lagged
WHERE month >= '2024-10'
ORDER BY channel, month
""")
Hint 1

monthly: GROUP BY channel, month with COUNT(DISTINCT order_id). An order has one channel, so no order is counted twice.

Hint 2

LAG(orders) OVER (PARTITION BY channel ORDER BY month). Without PARTITION BY, the lag would mix the two channels.

Solution
channel_mom_sql = """
WITH monthly AS (
SELECT channel, strftime('%Y-%m', order_date) AS month,
COUNT(DISTINCT order_id) AS orders
FROM orders
GROUP BY channel, month
),
lagged AS (
SELECT channel, month, orders,
LAG(orders) OVER (PARTITION BY channel ORDER BY month) AS prev_orders
FROM monthly
)
SELECT channel, month, orders, orders - prev_orders AS change
FROM lagged
WHERE month >= '2024-10'
ORDER BY channel, month
"""
show(channel_mom_sql)
rows = con.execute(channel_mom_sql).fetchall()
assert len(rows) == 6
assert all(row[3] is not None for row in rows)
Output
channel month orders change
online 2024-10 317 46
online 2024-11 554 237
online 2024-12 628 74
store 2024-10 358 13
store 2024-11 464 106
store 2024-12 609 145

How it works:

  1. monthly has one row per channel and month: 2 × 24 = 48 rows.
  2. PARTITION BY channel runs a separate LAG for each channel, so the online October looks back to the online September.
  3. The outer WHERE filters after the window, so October still has its September value. November jumps in both channels (Black Friday).

Alternative: pandas: monthly.groupby("channel")["orders"].diff() gives the change per channel in one call, after sorting by channel and month.

M30-C09 · Refactor: nested subqueries into a CTE chain

Section titled “M30-C09 · Refactor: nested subqueries into a CTE chain”
Core

Refactor: this query computes the average 2024 revenue per store in each region. It works, but it is hard to read from the inside out. Rewrite it as a chain of two CTEs, orders_2024 and per_store, plus a final SELECT. Assert that both versions return the same rows.

nested_sql = """
SELECT region, ROUND(AVG(store_revenue), 2) AS avg_store_revenue
FROM (
SELECT s.region, s.store_id, SUM(o.revenue) AS store_revenue
FROM (SELECT * FROM orders WHERE order_date >= '2024-01-01') AS o
JOIN stores AS s ON s.store_id = o.store_id
GROUP BY s.region, s.store_id
) AS per_store
GROUP BY region
ORDER BY avg_store_revenue DESC
"""
show(nested_sql)
Output
region avg_store_revenue
East 181588.36
South 160755.0
North 159243.14
West 148724.91
Expected output
region avg_store_revenue
East 181588.36
South 160755.0
North 159243.14
West 148724.91
Starter
cte_sql = """
WITH orders_2024 AS (
-- TODO: the innermost subquery
),
per_store AS (
-- TODO: the middle subquery, reading orders_2024
)
-- TODO: the outer query, reading per_store
"""
show(cte_sql)
Hint 1

Work from the inside out. Each subquery becomes one CTE, and its alias (o, per_store) becomes the CTE name or the alias you join with.

Hint 2

Compare the results with con.execute(nested_sql).fetchall() == con.execute(cte_sql).fetchall().

Solution
nested_sql = """
SELECT region, ROUND(AVG(store_revenue), 2) AS avg_store_revenue
FROM (
SELECT s.region, s.store_id, SUM(o.revenue) AS store_revenue
FROM (SELECT * FROM orders WHERE order_date >= '2024-01-01') AS o
JOIN stores AS s ON s.store_id = o.store_id
GROUP BY s.region, s.store_id
) AS per_store
GROUP BY region
ORDER BY avg_store_revenue DESC
"""
cte_sql = """
WITH orders_2024 AS (
SELECT * FROM orders WHERE order_date >= '2024-01-01'
),
per_store AS (
SELECT s.region, s.store_id, SUM(o.revenue) AS store_revenue
FROM orders_2024 AS o
JOIN stores AS s ON s.store_id = o.store_id
GROUP BY s.region, s.store_id
)
SELECT region, ROUND(AVG(store_revenue), 2) AS avg_store_revenue
FROM per_store
GROUP BY region
ORDER BY avg_store_revenue DESC
"""
show(cte_sql)
assert con.execute(cte_sql).fetchall() == con.execute(nested_sql).fetchall()
Output
region avg_store_revenue
East 181588.36
South 160755.0
North 159243.14
West 148724.91

How it works:

  1. The innermost subquery (2024 orders) becomes orders_2024. The middle one (revenue per store) becomes per_store. The outer query stays as it was.
  2. The CTE version reads top to bottom, in the order the data flows. You can test each step on its own.
  3. The engine produces the same plan for both versions, so the refactor changes readability, not speed. The assert proves the rows are equal.

Alternative: orders_2024 is not strictly needed: put WHERE o.order_date >= '2024-01-01' directly into per_store. Keep a separate step when several later steps share the same filtered rows.

M30-C10 · The weekday pattern in SQLite and DuckDB

Section titled “M30-C10 · The weekday pattern in SQLite and DuckDB”
Core

Compute the average daily revenue per weekday (Monday first, rounded to 1 decimal), once in SQLite on shop.db and once in DuckDB on data/sales.csv. Print the DuckDB result and assert that both engines agree.

Expected output
┌─────────┬───────────┬─────────────┐
│ iso_dow │ day │ avg_revenue │
│ int64 │ varchar │ double │
├─────────┼───────────┼─────────────┤
│ 1 │ Monday │ 4232.8 │
│ 2 │ Tuesday │ 3942.6 │
│ 3 │ Wednesday │ 4259.5 │
│ 4 │ Thursday │ 4416.3 │
│ 5 │ Friday │ 5597.5 │
│ 6 │ Saturday │ 6364.7 │
│ 7 │ Sunday │ 5635.8 │
└─────────┴───────────┴─────────────┘
Starter
sqlite_sql = """
WITH daily AS (
SELECT order_date, SUM(revenue) AS revenue FROM orders GROUP BY order_date
)
-- TODO: weekday number and average daily revenue
"""
duck_sql = """
WITH daily AS (
SELECT order_date, SUM(revenue) AS revenue
FROM 'data/sales.csv' GROUP BY order_date
)
-- TODO: isodow, dayname and average daily revenue, Monday first
"""
Hint 1

First total each day, then average the days. Averaging the order lines directly gives the average line, not the average day.

Hint 2

SQLite: strftime('%w', order_date) is '0' for Sunday … '6' for Saturday. DuckDB: isodow(order_date) is 1 for Monday … 7 for Sunday, and dayname(order_date) gives the name.

Solution
sqlite_sql = """
WITH daily AS (
SELECT order_date, SUM(revenue) AS revenue FROM orders GROUP BY order_date
)
SELECT CAST(strftime('%w', order_date) AS INTEGER) AS dow,
ROUND(AVG(revenue), 1) AS avg_revenue
FROM daily
GROUP BY dow
"""
duck_sql = """
WITH daily AS (
SELECT order_date, SUM(revenue) AS revenue
FROM 'data/sales.csv' GROUP BY order_date
)
SELECT isodow(order_date) AS iso_dow, dayname(order_date) AS day,
ROUND(AVG(revenue), 1) AS avg_revenue
FROM daily
GROUP BY ALL
ORDER BY iso_dow
"""
duck_rel = duckdb.sql(duck_sql)
duck_rel.show(max_width=100)
sqlite_avg = {dow: avg for dow, avg in con.execute(sqlite_sql)}
for iso_dow, _, avg in duck_rel.fetchall():
assert abs(sqlite_avg[iso_dow % 7] - avg) < 0.01
Output
┌─────────┬───────────┬─────────────┐
│ iso_dow │ day │ avg_revenue │
│ int64 │ varchar │ double │
├─────────┼───────────┼─────────────┤
│ 1 │ Monday │ 4232.8 │
│ 2 │ Tuesday │ 3942.6 │
│ 3 │ Wednesday │ 4259.5 │
│ 4 │ Thursday │ 4416.3 │
│ 5 │ Friday │ 5597.5 │
│ 6 │ Saturday │ 6364.7 │
│ 7 │ Sunday │ 5635.8 │
└─────────┴───────────┴─────────────┘

How it works:

  1. Both queries first build one row per day, then average per weekday.
  2. SQLite numbers days 0 (Sunday) to 6. ISO numbers them 1 (Monday) to 7 (Sunday). iso_dow % 7 maps ISO 7 to 0 and leaves 1–6 unchanged, so the two numberings line up.
  3. GROUP BY ALL is a DuckDB shortcut that groups by every non-aggregated column. Saturday is the peak and Tuesday the low.
  4. The assert uses a tolerance instead of ==. DuckDB adds numbers in parallel threads, so the order of the additions, and with it the last digits of a float sum, can change from run to run. The exact Wednesday average is 4259.465 USD, right on a rounding edge at 2 decimals, so a 2-decimal result could flip between .46 and .47. One decimal is stable here. For exact money sums, DuckDB has the DECIMAL type.

Alternative: in pandas, daily.groupby(daily["order_date"].dt.dayofweek)["revenue"].mean() uses 0 for Monday, a third numbering. Always check which day is 0.

M30-C11 · A pandas → SQL → pandas round trip

Section titled “M30-C11 · A pandas → SQL → pandas round trip”
Core

Load data/customers.csv with pandas and write it into an in-memory SQLite database with to_sql. Then query the churn rate per contract for customers with at least 12 months of tenure, passing 12 as a parameter, and read the result with pd.read_sql_query. Assert that pandas groupby gives the same rates.

Expected output
rows written: 5000
contract customers churn_pct
0 month-to-month 1252 17.8
1 one-year 1024 7.9
2 two-year 884 3.2
Starter
customers = pd.read_csv("data/customers.csv")
mem = sqlite3.connect(":memory:")
# TODO: write customers into mem
# TODO: read_sql_query with params=(12,)
# TODO: the same rates in pandas, then compare
Hint 1

customers.to_sql("customers", mem, index=False) returns the number of rows written.

Hint 2

pd.read_sql_query(sql, mem, params=(12,)) with WHERE tenure_months >= ?. In pandas: customers[customers["tenure_months"] >= 12].groupby("contract")["churned"].mean().

Solution
customers = pd.read_csv("data/customers.csv")
mem = sqlite3.connect(":memory:")
written = customers.to_sql("customers", mem, index=False)
print("rows written:", written)
rates_sql = """
SELECT contract, COUNT(*) AS customers,
ROUND(100.0 * AVG(churned), 1) AS churn_pct
FROM customers
WHERE tenure_months >= ?
GROUP BY contract
ORDER BY churn_pct DESC
"""
sql_rates = pd.read_sql_query(rates_sql, mem, params=(12,))
print(sql_rates)
loyal = customers[customers["tenure_months"] >= 12]
pandas_rates = (loyal.groupby("contract")["churned"].mean() * 100).round(1)
assert (sql_rates.set_index("contract")["churn_pct"] == pandas_rates).all()
mem.close()
Output
rows written: 5000
contract customers churn_pct
0 month-to-month 1252 17.8
1 one-year 1024 7.9
2 two-year 884 3.2

How it works:

  1. to_sql creates the table customers in mem with one column per DataFrame column and inserts all rows.
  2. params=(12,) fills the ? placeholder. Change the tenure without touching the SQL text.
  3. Comparing two Series with == aligns them by index (contract), so the row order does not matter. Month-to-month churn stays the highest even among customers who have stayed a year.

Alternative: skip the copy and let DuckDB read the DataFrame by name: duckdb.sql("SELECT ... FROM customers WHERE tenure_months >= ?", params=[12]).df().

M30-C12 · Choose a method: the latest line of each customer

Section titled “M30-C12 · Choose a method: the latest line of each customer”
Core

Choose a method and justify it: you need exactly one row per customer, their most recent order line. Approach A finds MAX(order_date) per customer and joins it back to orders. Approach B numbers the lines of each customer with ROW_NUMBER(), newest first, and keeps number 1. Run both, count their rows and the customers, and decide which one is correct.

Expected output
customers: 3254
approach A rows: 4437
approach B rows: 3254
Starter
approach_a = """
WITH last_day AS (
SELECT customer_id, MAX(order_date) AS order_date
FROM orders GROUP BY customer_id
)
SELECT o.* FROM orders AS o
JOIN last_day AS d
ON d.customer_id = o.customer_id AND d.order_date = o.order_date
"""
approach_b = """
-- TODO: ROW_NUMBER() per customer, newest first, keep 1
"""
# TODO: count customers, rows of A and rows of B
Hint 1

Wrap each approach in SELECT COUNT(*) FROM (...) to count its rows.

Hint 2

ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, line_id DESC). The second sort column decides between lines of the same day.

Solution
approach_a = """
WITH last_day AS (
SELECT customer_id, MAX(order_date) AS order_date
FROM orders GROUP BY customer_id
)
SELECT o.* FROM orders AS o
JOIN last_day AS d
ON d.customer_id = o.customer_id AND d.order_date = o.order_date
"""
approach_b = """
WITH numbered AS (
SELECT *, ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY order_date DESC, line_id DESC) AS pos
FROM orders
)
SELECT * FROM numbered WHERE pos = 1
"""
(n_customers,) = con.execute(
"SELECT COUNT(DISTINCT customer_id) FROM orders"
).fetchone()
(rows_a,) = con.execute(f"SELECT COUNT(*) FROM ({approach_a})").fetchone()
(rows_b,) = con.execute(f"SELECT COUNT(*) FROM ({approach_b})").fetchone()
print("customers:", n_customers)
print("approach A rows:", rows_a)
print("approach B rows:", rows_b)
assert rows_b == n_customers
assert rows_a > n_customers
Output
customers: 3254
approach A rows: 4437
approach B rows: 3254

How it works:

  1. Approach A matches every line on the customer’s last day. A customer whose last order had 3 lines, or who placed 2 orders that day, gets several rows: a fan-out caused by ties.
  2. Approach B gives each line of a customer a unique number. line_id DESC breaks ties between lines of the same day, so exactly one line per customer gets number 1.
  3. Decision: approach B. It returns exactly one row per customer by construction, and it is deterministic. Use approach A only when you want all lines of the last day.

Alternative: in DuckDB, SELECT * FROM orders QUALIFY ROW_NUMBER() OVER (...) = 1, or arg_max(line_id, order_date) grouped by customer. In pandas: orders.sort_values(["order_date", "line_id"]).groupby("customer_id").tail(1).

M30-X01 · 90-day repeat purchase by cohort

Section titled “M30-X01 · 90-day repeat purchase by cohort”
Challenge

A cohort is a group of customers who share a starting point. Group the customers by the quarter of their first order (2023-Q1 … 2024-Q3). For each cohort, show the number of customers, how many ordered again on a later day within 90 days of their first order, and that share in percent. Stop at 2024-Q3, because a later cohort has not had 90 days to come back before the data ends.

Expected output
cohort customers returned_90d returned_pct
2023-Q1 731 394 53.9
2023-Q2 499 247 49.5
2023-Q3 335 153 45.7
2023-Q4 358 159 44.4
2024-Q1 236 102 43.2
2024-Q2 303 118 38.9
2024-Q3 318 121 38.1
Starter
show("""
WITH firsts AS (
-- TODO: first order date per customer
),
flagged AS (
-- TODO: 1 if another order exists 1-90 days after the first, else 0
)
-- TODO: cohort label, customers, returned, share; cohorts up to 2024-Q3
""")
Hint 1

firsts: SELECT customer_id, MIN(order_date) AS first_date FROM orders GROUP BY customer_id.

Hint 2

EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = f.customer_id AND o.order_date > f.first_date AND o.order_date <= date(f.first_date, '+90 days')) is 1 or 0 in SQLite.

Hint 3

The quarter of a month m is (m + 2) / 3 with integer division. Build the label with ||, the SQL string concatenation operator: strftime('%Y', first_date) || '-Q' || ....

Solution
cohort_sql = """
WITH firsts AS (
SELECT customer_id, MIN(order_date) AS first_date
FROM orders
GROUP BY customer_id
),
flagged AS (
SELECT f.customer_id, f.first_date,
EXISTS (SELECT 1 FROM orders AS o
WHERE o.customer_id = f.customer_id
AND o.order_date > f.first_date
AND o.order_date <= date(f.first_date, '+90 days')
) AS returned
FROM firsts AS f
WHERE f.first_date < '2024-10-01'
)
SELECT strftime('%Y', first_date) || '-Q'
|| ((CAST(strftime('%m', first_date) AS INTEGER) + 2) / 3) AS cohort,
COUNT(*) AS customers,
SUM(returned) AS returned_90d,
ROUND(100.0 * AVG(returned), 1) AS returned_pct
FROM flagged
GROUP BY cohort
ORDER BY cohort
"""
show(cohort_sql)
rows = con.execute(cohort_sql).fetchall()
assert len(rows) == 7
assert rows[0][0] == "2023-Q1" and rows[-1][0] == "2024-Q3"
assert all(0 <= row[3] <= 100 for row in rows)
Output
cohort customers returned_90d returned_pct
2023-Q1 731 394 53.9
2023-Q2 499 247 49.5
2023-Q3 335 153 45.7
2023-Q4 358 159 44.4
2024-Q1 236 102 43.2
2024-Q2 303 118 38.9
2024-Q3 318 121 38.1

How it works:

  1. firsts finds each customer’s first order date. WHERE first_date < '2024-10-01' keeps the cohorts that have a full 90-day window before 2024-12-31.
  2. The correlated EXISTS checks for an order on a later day, at most 90 days after the first one. date(first_date, '+90 days') does the date arithmetic on ISO text.
  3. (month + 2) / 3 uses SQLite’s integer division on purpose: months 1–3 give 1, 4–6 give 2, and so on.
  4. The first cohort is much larger, because every customer who existed before 2023 places a “first order” in the data early in 2023. The early cohorts mix new and old customers, so compare the later cohorts with each other.

Alternative: use LEAD(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) to get the next order date, then compare it with the first. In DuckDB, date_diff('day', first_date, next_date) <= 90 reads more clearly than SQLite’s date(first_date, '+90 days') comparison.

Challenge

Market basket analysis looks for products that appear in the same order. Find the five product pairs that appear together in the most orders. Show both product names and the number of orders. Each pair must appear once (not as A–B and B–A).

Expected output
product_a product_b orders
Wireless Earbuds Non-Slip Yoga Mat 56
Wireless Earbuds Organic Cotton T-Shirt 55
Wireless Earbuds Cotton Bed Sheet Set 53
Wireless Earbuds Noise-Cancelling Headphones 52
Organic Cotton T-Shirt Non-Slip Yoga Mat 45
orders with 2+ lines: 4113
Starter
show("""
SELECT p1.product AS product_a, p2.product AS product_b, COUNT(*) AS orders
FROM orders AS o1
JOIN orders AS o2 ON -- TODO: same order, each pair once
-- TODO: join products twice for the names
GROUP BY o1.product_id, o2.product_id
ORDER BY orders DESC, product_a
LIMIT 5
""")
Hint 1

A self-join joins a table to itself under two aliases. o1.order_id = o2.order_id pairs the lines of the same order.

Hint 2

o1.product_id < o2.product_id removes the pairs of a line with itself and keeps only one ordering of each pair. An order has distinct products, so each order counts once per pair.

Solution
pairs_sql = """
SELECT p1.product AS product_a, p2.product AS product_b, COUNT(*) AS orders
FROM orders AS o1
JOIN orders AS o2
ON o2.order_id = o1.order_id AND o1.product_id < o2.product_id
JOIN products AS p1 ON p1.product_id = o1.product_id
JOIN products AS p2 ON p2.product_id = o2.product_id
GROUP BY o1.product_id, o2.product_id
ORDER BY orders DESC, product_a
LIMIT 5
"""
show(pairs_sql)
(multi_line_orders,) = con.execute("""
SELECT COUNT(*) FROM (
SELECT order_id FROM orders GROUP BY order_id HAVING COUNT(*) > 1)
""").fetchone()
print("orders with 2+ lines:", multi_line_orders)
rows = con.execute(pairs_sql).fetchall()
assert len(rows) == 5
assert all(a[2] >= b[2] for a, b in zip(rows, rows[1:]))
Output
product_a product_b orders
Wireless Earbuds Non-Slip Yoga Mat 56
Wireless Earbuds Organic Cotton T-Shirt 55
Wireless Earbuds Cotton Bed Sheet Set 53
Wireless Earbuds Noise-Cancelling Headphones 52
Organic Cotton T-Shirt Non-Slip Yoga Mat 45
orders with 2+ lines: 4113

How it works:

  1. The self-join pairs every two lines of the same order. An order with 3 lines gives 3 pairs.
  2. o1.product_id < o2.product_id keeps each pair once, in one fixed order, and drops a line paired with itself.
  3. Two more joins add the names. GROUP BY the two ids counts the orders per pair.
  4. Wireless Earbuds, the product with the most lines, appears in four of the five top pairs. Pair counts grow with how often each product sells. A fair comparison divides by what you would expect by chance (the lift), which is the next step of a real basket analysis.

Alternative: pandas: lines = orders[["order_id", "product_id"]], then lines.merge(lines, on="order_id").query("product_id_x < product_id_y") and value_counts() on the two id columns.

M30-X03 · Reconcile the monthly report files with the sales data

Section titled “M30-X03 · Reconcile the monthly report files with the sales data”
Challenge

The six files data/reports/2024-01.csv … 2024-06.csv are monthly extracts that someone sent by email. Check them against data/sales.csv with DuckDB. For each month, show the report lines, how many of them match a sales line (same order_id and product), the revenue difference on the matched lines, and the report’s revenue as a share of the full month’s revenue.

Expected output
┌─────────┬──────────────┬─────────┬──────────────┬──────────────┐
│ month │ report_lines │ matched │ revenue_diff │ coverage_pct │
│ varchar │ int64 │ int64 │ double │ double │
├─────────┼──────────────┼─────────┼──────────────┼──────────────┤
│ 2024-01 │ 48 │ 48 │ 0.0 │ 11.8 │
│ 2024-02 │ 48 │ 48 │ 0.0 │ 4.4 │
│ 2024-03 │ 47 │ 47 │ 0.0 │ 8.4 │
│ 2024-04 │ 52 │ 52 │ 0.0 │ 9.5 │
│ 2024-05 │ 47 │ 47 │ 0.0 │ 5.2 │
│ 2024-06 │ 55 │ 55 │ 0.0 │ 5.5 │
└─────────┴──────────────┴─────────┴──────────────┴──────────────┘
Starter
reconcile = duckdb.sql("""
WITH report AS (
SELECT * FROM read_csv('data/reports/2024-*.csv', union_by_name = true)
),
sales AS (
SELECT * FROM 'data/sales.csv'
WHERE order_date >= DATE '2024-01-01' AND order_date < DATE '2024-07-01'
),
matched AS (
-- TODO: report LEFT JOIN sales on both keys
),
month_totals AS (
-- TODO: full sales revenue per month
)
-- TODO: one row per month
""")
reconcile.show(max_width=100)
Hint 1

matched: report AS r LEFT JOIN sales AS s ON s.order_id = r.order_id AND s.product = r.product, keeping r.* and s.revenue AS sales_revenue. An unmatched report line gets NULL.

Hint 2

COUNT(sales_revenue) counts matched lines only. SUM(revenue - sales_revenue) adds the differences of the matched lines.

Hint 3

Group both sides by strftime(order_date, '%Y-%m') and join month_totals on that month label.

Solution
reconcile = duckdb.sql("""
WITH report AS (
SELECT * FROM read_csv('data/reports/2024-*.csv', union_by_name = true)
),
sales AS (
SELECT * FROM 'data/sales.csv'
WHERE order_date >= DATE '2024-01-01' AND order_date < DATE '2024-07-01'
),
matched AS (
SELECT r.*, s.revenue AS sales_revenue
FROM report AS r
LEFT JOIN sales AS s ON s.order_id = r.order_id AND s.product = r.product
),
month_totals AS (
SELECT strftime(order_date, '%Y-%m') AS month, SUM(revenue) AS month_revenue
FROM sales
GROUP BY month
)
SELECT strftime(m.order_date, '%Y-%m') AS month,
COUNT(*) AS report_lines,
COUNT(m.sales_revenue) AS matched,
ROUND(SUM(m.revenue - m.sales_revenue), 2) AS revenue_diff,
ROUND(100 * SUM(m.revenue) / ANY_VALUE(t.month_revenue), 1) AS coverage_pct
FROM matched AS m
JOIN month_totals AS t ON t.month = strftime(m.order_date, '%Y-%m')
GROUP BY 1
ORDER BY 1
""")
reconcile.show(max_width=100)
rows = reconcile.fetchall()
assert sum(row[1] for row in rows) == 297
assert all(row[1] == row[2] for row in rows)
assert all(row[3] == 0 for row in rows)
Output
┌─────────┬──────────────┬─────────┬──────────────┬──────────────┐
│ month │ report_lines │ matched │ revenue_diff │ coverage_pct │
│ varchar │ int64 │ int64 │ double │ double │
├─────────┼──────────────┼─────────┼──────────────┼──────────────┤
│ 2024-01 │ 48 │ 48 │ 0.0 │ 11.8 │
│ 2024-02 │ 48 │ 48 │ 0.0 │ 4.4 │
│ 2024-03 │ 47 │ 47 │ 0.0 │ 8.4 │
│ 2024-04 │ 52 │ 52 │ 0.0 │ 9.5 │
│ 2024-05 │ 47 │ 47 │ 0.0 │ 5.2 │
│ 2024-06 │ 55 │ 55 │ 0.0 │ 5.5 │
└─────────┴──────────────┴─────────┴──────────────┴──────────────┘

How it works:

  1. union_by_name = true reads the six files as one table, although the April file has its columns in a different order.
  2. The left join keeps every report line. The match uses two keys, because order_id alone is not unique in the sales data.
  3. Every report line matches and every revenue difference is 0: the reports are clean extracts. They cover only 4% to 12% of each month’s revenue, so they are samples, not monthly totals.
  4. ANY_VALUE(t.month_revenue) takes the month total, which is the same on every row of the group. GROUP BY 1 groups by the first column of the SELECT.

Alternative: an anti-join lists the problem lines directly: SELECT r.* FROM report r WHERE NOT EXISTS (SELECT 1 FROM sales s WHERE s.order_id = r.order_id AND s.product = r.product). Here it returns no rows.

M30-X04 · A safe, reusable report function

Section titled “M30-X04 · A safe, reusable report function”
Challenge

Write revenue_report(con, group_by, start, end, top=3). It returns a DataFrame with the revenue and lines per group for orders with start <= order_date < end, largest revenue first, limited to top rows. group_by is one of region, category, channel or store_id; any other value raises ValueError. Dates and top must go through placeholders. Print two reports and the error message for the input "region; DROP TABLE orders".

Expected output
category lines revenue
0 Electronics 355 149266.09
1 Home 229 54659.12
2 Sports 144 25150.59
store_id lines revenue
0 S09 9 2797.88
1 S07 17 2613.58
ValueError: group_by must be one of ['category', 'channel', 'region', 'store_id']
Starter
GROUP_COLUMNS = {
"region": "s.region",
"category": "p.category",
"channel": "o.channel",
"store_id": "o.store_id",
}
def revenue_report(
con: sqlite3.Connection, group_by: str, start: str, end: str, top: int = 3
) -> pd.DataFrame:
# TODO: check group_by against the allowlist
# TODO: build the SQL with the chosen column and ? placeholders
# TODO: pd.read_sql_query with params
...
Hint 1

The dict is the allowlist and maps each public name to a qualified column. Look it up with GROUP_COLUMNS[group_by] after an if group_by not in GROUP_COLUMNS: raise ValueError(...).

Hint 2

Join both dimension tables always, so every allowed column exists. The values go in params=(start, end, top), in the order of the ? marks.

Solution
GROUP_COLUMNS = {
"region": "s.region",
"category": "p.category",
"channel": "o.channel",
"store_id": "o.store_id",
}
def revenue_report(
con: sqlite3.Connection, group_by: str, start: str, end: str, top: int = 3
) -> pd.DataFrame:
"""Revenue and lines per group for start <= order_date < end."""
if group_by not in GROUP_COLUMNS:
raise ValueError(f"group_by must be one of {sorted(GROUP_COLUMNS)}")
column = GROUP_COLUMNS[group_by]
sql = f"""
SELECT {column} AS {group_by},
COUNT(*) AS lines,
ROUND(SUM(o.revenue), 2) AS revenue
FROM orders AS o
JOIN stores AS s ON s.store_id = o.store_id
JOIN products AS p ON p.product_id = o.product_id
WHERE o.order_date >= ? AND o.order_date < ?
GROUP BY {column}
ORDER BY revenue DESC
LIMIT ?
"""
return pd.read_sql_query(sql, con, params=(start, end, top))
print(revenue_report(con, "category", "2024-11-01", "2024-12-01"))
print(revenue_report(con, "store_id", "2024-12-24", "2024-12-27", top=2))
try:
revenue_report(con, "region; DROP TABLE orders", "2024-01-01", "2025-01-01")
except ValueError as error:
print("ValueError:", error)
report = revenue_report(con, "channel", "2023-01-01", "2025-01-01")
assert report["lines"].sum() == 20228
Output
category lines revenue
0 Electronics 355 149266.09
1 Home 229 54659.12
2 Sports 144 25150.59
store_id lines revenue
0 S09 9 2797.88
1 S07 17 2613.58
ValueError: group_by must be one of ['category', 'channel', 'region', 'store_id']

How it works:

  1. The allowlist check runs first. A name that is not a key of GROUP_COLUMNS never reaches the SQL text.
  2. The f-string inserts only a column name from the dict, written by you. The dates and the limit go through ? placeholders, in order.
  3. Both joins are always present, so each allowed column exists. The joins are on primary keys, so they cannot change the line counts.
  4. The second report passes top=2. The limit is a value, so it goes through a placeholder like the dates.

Alternative: sqlite3 also accepts named placeholders: WHERE o.order_date >= :start AND o.order_date < :end LIMIT :top with params={"start": start, "end": end, "top": top}. A typed CLI around this function would use argparse with choices=sorted(GROUP_COLUMNS) (module 08).

Challenge

Flag the days whose revenue is unusually high compared with the 28 days before. For each day, compute the mean and the sample standard deviation of the previous 28 days (not including the day itself) and the z-score (revenue - mean) / std. List the days of 2024 with a z-score above 3, highest first, using DuckDB on data/sales.csv.

Expected output
┌────────────┬──────────┬──────────┬───────────────┬────────┐
│ order_date │ day │ revenue │ trailing_mean │ z │
│ date │ varchar │ double │ double │ double │
├────────────┼──────────┼──────────┼───────────────┼────────┤
│ 2024-11-29 │ Friday │ 33619.18 │ 7757.7 │ 9.12 │
│ 2024-05-11 │ Saturday │ 12646.06 │ 3672.63 │ 5.14 │
│ 2024-11-02 │ Saturday │ 16896.3 │ 5584.94 │ 4.96 │
│ 2024-07-21 │ Sunday │ 11860.26 │ 4618.6 │ 3.77 │
└────────────┴──────────┴──────────┴───────────────┴────────┘
Starter
flags = duckdb.sql("""
WITH daily AS (
SELECT order_date, ROUND(SUM(revenue), 2) AS revenue
FROM 'data/sales.csv' GROUP BY order_date
),
scored AS (
SELECT order_date, revenue,
-- TODO: trailing mean and std over the 28 previous rows
FROM daily
)
-- TODO: z-score, 2024 only, z > 3, highest first
""")
flags.show(max_width=100)
Hint 1

The frame ROWS BETWEEN 28 PRECEDING AND 1 PRECEDING covers the 28 days before the current one. Define it once with WINDOW w AS (ORDER BY order_date ROWS BETWEEN 28 PRECEDING AND 1 PRECEDING).

Hint 2

AVG(revenue) OVER w and STDDEV_SAMP(revenue) OVER w. Filter on the year in the outer query, so January 2024 still sees December 2023.

Solution
flags = duckdb.sql("""
WITH daily AS (
SELECT order_date, ROUND(SUM(revenue), 2) AS revenue
FROM 'data/sales.csv' GROUP BY order_date
),
scored AS (
SELECT order_date, revenue,
AVG(revenue) OVER w AS trailing_mean,
STDDEV_SAMP(revenue) OVER w AS trailing_std
FROM daily
WINDOW w AS (ORDER BY order_date ROWS BETWEEN 28 PRECEDING AND 1 PRECEDING)
)
SELECT order_date, dayname(order_date) AS day,
ROUND(revenue, 2) AS revenue,
ROUND(trailing_mean, 2) AS trailing_mean,
ROUND((revenue - trailing_mean) / trailing_std, 2) AS z
FROM scored
WHERE year(order_date) = 2024
AND (revenue - trailing_mean) / trailing_std > 3
ORDER BY z DESC
""")
flags.show(max_width=100)
rows = flags.fetchall()
assert len(rows) == 4
assert str(rows[0][0]) == "2024-11-29"
assert all(row[4] > 3 for row in rows)
Output
┌────────────┬──────────┬──────────┬───────────────┬────────┐
│ order_date │ day │ revenue │ trailing_mean │ z │
│ date │ varchar │ double │ double │ double │
├────────────┼──────────┼──────────┼───────────────┼────────┤
│ 2024-11-29 │ Friday │ 33619.18 │ 7757.7 │ 9.12 │
│ 2024-05-11 │ Saturday │ 12646.06 │ 3672.63 │ 5.14 │
│ 2024-11-02 │ Saturday │ 16896.3 │ 5584.94 │ 4.96 │
│ 2024-07-21 │ Sunday │ 11860.26 │ 4618.6 │ 3.77 │
└────────────┴──────────┴──────────┴───────────────┴────────┘

How it works:

  1. daily has one row per day. Every day has sales, so 28 rows are 28 days. Rounding the daily totals to cents makes the inputs of the windows identical in every run, although DuckDB adds the lines in parallel.
  2. The frame ends at 1 PRECEDING, so a day’s own revenue does not inflate its baseline. A spike that is part of its own baseline is harder to detect.
  3. The year filter runs in the outer query, after the windows, so the first days of 2024 still use the end of 2023 as their baseline.
  4. Black Friday 2024 tops the list with a z-score above 9. The other three are weekend days with several TV and laptop lines: a few high-price electronics sales move daily revenue a lot. A z-score finds candidates; a person still checks them before calling a day an anomaly.

Alternative: pandas: prev = daily["revenue"].shift(1).rolling(28), then z = (daily["revenue"] - prev.mean()) / prev.std(). The shift(1) excludes the current day, like 1 PRECEDING.