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:
- Read the task and the expected output.
- Copy the setup block below into a script, then the starter code under it. Replace each to-do comment with your code.
- Run the script. Compare your output with the expected output.
- 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 duckdbimport 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
Section titled “Warm-up”M30-W01 · List the stores of one region
Section titled “M30-W01 · List the stores of one region”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.
store_id city size_sqm openedS10 Seattle 2480 2010-06-19S11 San Francisco 1890 2014-07-26S12 Denver 1350 2023-06-15show(""" 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]store_id city size_sqm openedS10 Seattle 2480 2010-06-19S11 San Francisco 1890 2014-07-26S12 Denver 1350 2023-06-15How it works:
FROM storesnames the table.WHERE region = 'West'keeps the three West stores.ORDER BY size_sqm DESCsorts by floor area, largest first.- 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”List the five products with the highest unit_price: product_id, product, category and unit_price.
product_id product category unit_priceP003 55-inch 4K Smart TV Electronics 1299.0P004 14-inch Ultrabook Laptop Electronics 1149.0P006 Espresso Machine Home 349.0P007 Robot Vacuum Home 299.99P018 Adjustable Dumbbells Sports 279.0show(""" 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) == 5assert rows[0][0] == "P003"assert all(a[3] >= b[3] for a, b in zip(rows, rows[1:]))product_id product category unit_priceP003 55-inch 4K Smart TV Electronics 1299.0P004 14-inch Ultrabook Laptop Electronics 1149.0P006 Espresso Machine Home 349.0P007 Robot Vacuum Home 299.99P018 Adjustable Dumbbells Sports 279.0How it works:
ORDER BY unit_price DESCputs the most expensive product first.LIMIT 5keeps the first five rows of the sorted result.LIMITalways runs last.- 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”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.
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 itHint 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)all_rows known missing eq_null first_known 5000 4990 10 0 n/a(None, 1, 0, None)How it works:
COUNT(*)counts all 5,000 rows.COUNT(total_charges)skips the 10 NULLs.total_charges IS NULLis 1 for the 10 missing values, so theSUMis 10.total_charges = NULLis never true, so the filtered count is 0.COALESCEreturns its first argument that is not NULL:'n/a'.NULL + 1is NULL: unknown plus 1 is unknown.NULL OR 1is 1, because one true side is enough.NULL AND 0is 0, because one false side is enough.NULL = NULLis NULL.sqlite3returns NULL asNone.
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.
M30-W04 · Lines and revenue per channel
Section titled “M30-W04 · Lines and revenue per channel”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.
channel lines revenue avg_linestore 11733 2077057.36 177.03online 8495 1519466.47 178.87show(""" 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) == 20228assert abs(sum(row[2] for row in rows) - 3596523.83) < 0.05channel lines revenue avg_linestore 11733 2077057.36 177.03online 8495 1519466.47 178.87How it works:
GROUP BY channelsplits the 20,228 lines into two groups.- Each aggregate runs once per group.
AVG(revenue)equalsSUM(revenue) / COUNT(*). - 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”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""")contract churn_pctmonth-to-month 29one-year 8two-year 3Change the query so that it prints:
contract churn_pctmonth-to-month 29.6one-year 8.8two-year 3.2show(""" 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}contract churn_pctmonth-to-month 29.6one-year 8.8two-year 3.2How it works:
SUM(churned) * 100is an integer andCOUNT(*)is an integer, so SQLite used integer division and dropped the decimals.100.0is a float.100.0 * SUM(churned)is a float, so the division keeps its decimals.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”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""")sqlite3.OperationalError: misuse of aggregate: COUNT()Fix it, and sort the stores by their number of lines, largest first:
store_id linesS07 2541S01 2220S04 2199S10 2190show(""" 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)store_id linesS07 2541S01 2220S04 2199S10 2190How it works:
- The logical order is
FROM→WHERE→GROUP BY→HAVING→SELECT→ORDER BY. An aggregate needs groups, so it cannot appear inWHERE. HAVING COUNT(*) > 2000keeps the groups whose count is above 2,000.- 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.
M30-W07 · Price bands with CASE
Section titled “M30-W07 · Price bands with CASE”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.
band products lowest highestbudget 9 14.99 29.99mid 12 32.0 129.99premium 9 189.0 1299.0show(""" 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) == 30band products lowest highestbudget 9 14.99 29.99mid 12 32.0 129.99premium 9 189.0 1299.0How it works:
- The CASE expression gives each product one band. The first true
WHENwins. GROUP BY bandgroups by the new column. SQLite allows the alias inGROUP BY.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”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.
C00042 -> standardC99999 -> Nonex' OR '1'='1 -> Nonedef 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 Noneassert customer_plan("x' OR '1'='1") is NoneC00042 -> standardC99999 -> Nonex' OR '1'='1 -> NoneHow it works:
- The
?marks where the value goes. The value travels separately from the SQL text. - The engine compares
customer_idwith the whole attack string as plain text. No customer has that id, so the result isNone. fetchone()returnsNoneat 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.
M30-W09 · DuckDB on a CSV file
Section titled “M30-W09 · DuckDB on a CSV file”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.
┌─────────────┬──────────┬───────────┐│ 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 │└─────────────┴──────────┴───────────┘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) == 6assert rows[0][0] == "Electronics"assert all(row[1] == 5 for row in rows)┌─────────────┬──────────┬───────────┐│ 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:
- DuckDB reads the CSV file, detects the header and the column types, and runs the query on it.
.show(max_width=100)prints a box with the column names and types..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”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.
region lines revenueEast 5396 993683.72South 5144 891766.07North 4966 888229.47West 4722 822844.57largest difference: 0.0region_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 compareHint 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.005region lines revenueEast 5396 993683.72South 5144 891766.07North 4966 888229.47West 4722 822844.57largest difference: 0.0How it works:
- The join adds
s.regionto every order line.GROUP BY s.regionmakes four groups. pd.read_sql_queryreturns the SQL result as a DataFrame.set_index("region")["revenue"]turns it into a Series keyed by region.- 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”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.
category online store online_pctBeauty 63758.35 86659.41 42.4Electronics 767072.48 1041035.69 42.4Clothing 133153.32 181533.3 42.3Home 284066.0 388228.61 42.3Books 44644.66 62263.46 41.8Sports 226771.66 317336.89 41.7show(""" 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) == 6assert result["online_pct"].between(0, 100).all()assert abs((result["online"] + result["store"]).sum() - 3596523.83) < 0.05category online store online_pctBeauty 63758.35 86659.41 42.4Electronics 767072.48 1041035.69 42.4Clothing 133153.32 181533.3 42.3Home 284066.0 388228.61 42.3Books 44644.66 62263.46 41.8Sports 226771.66 317336.89 41.7How it works:
- Each
SUM(CASE ...)adds the revenue of one channel and 0 for the other lines. One pass over the table fills both columns. - The CTE
totalsnames the two sums, so the outer query can use them in the share formula. 100.0keeps 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").
M30-C03 · Lapsed customers
Section titled “M30-C03 · Lapsed customers”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.
status customers churn_pct avg_loginsactive 1524 9.4 11.8lapsed 399 10.8 12.3show(""" 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_2023status customers churn_pct avg_loginsactive 1524 9.4 11.8lapsed 399 10.8 12.3How it works:
WHERE EXISTS (...)is a semi-join: it keeps each customer with at least one 2023 order, once.- The CASE uses a second
EXISTSto test for a 2024 order. No 2024 order means lapsed: an anti-join written as a CASE branch. - 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”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""")plan customers online_buyersbasic 990 990premium 525 525standard 961 961Fix the query so that it prints:
plan customers online_buyersbasic 2028 990premium 990 525standard 1982 961show(""" 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) == 5000assert all(row[2] < row[1] for row in rows)plan customers online_buyersbasic 2028 990premium 990 525standard 1982 961How it works:
- In the bug,
WHERE o.channel = 'online'runs after the join. Customers without an online order haveo.channelNULL, the condition is unknown, andWHEREdrops them. The left join behaves like an inner join. - In the
ONclause, the condition only decides which orders match. Unmatched customers stay, with NULLs. 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”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”.
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 itHint 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}INNER 4LEFT 5RIGHT 5FULL 6CROSS 16How it works:
- Inner: key 1 gives 2 × 1 = 2 pairs and key 2 gives 1 × 2 = 2 pairs: 4 rows. Duplicates multiply.
- Left: the 4 pairs plus
a4(key 3) with NULLs: 5. Right: the 4 pairs plusb4(key 4): 5. - Full: the 4 pairs plus both unmatched rows: 6. Cross: every pair, 4 × 4 = 16.
- 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”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().
region customer_id revenue ordersEast C01364 16023.65 44North C01766 13341.26 36West C01656 12785.14 24South C00587 10590.79 32show(""" 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)region customer_id revenue ordersEast C01364 16023.65 44North C01766 13341.26 36West C01656 12785.14 24South C00587 10590.79 32How it works:
totalshas one row per customer.COUNT(DISTINCT o.order_id)counts orders, not lines: an order can have up to 3 lines.rankednumbers the customers in each region, best first.SELECT *keeps all the columns oftotals.- 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”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).
month revenue ytd ytd_pct01 119596.89 119596.89 6.102 106320.41 225917.3 11.603 145567.22 371484.52 19.004 114917.5 486402.02 24.905 128716.36 615118.38 31.506 155854.41 770972.79 39.507 148989.14 919961.93 47.208 151791.33 1071753.26 54.909 141654.74 1213408.0 62.210 166147.92 1379555.92 70.711 268466.55 1648022.47 84.512 302911.77 1950934.24 100.0show(""" 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) == 12assert rows[-1][3] == 100.0assert abs(rows[-1][2] - 1950934.24) < 0.01month revenue ytd ytd_pct01 119596.89 119596.89 6.102 106320.41 225917.3 11.603 145567.22 371484.52 19.004 114917.5 486402.02 24.905 128716.36 615118.38 31.506 155854.41 770972.79 39.507 148989.14 919961.93 47.208 151791.33 1071753.26 54.909 141654.74 1213408.0 62.210 166147.92 1379555.92 70.711 268466.55 1648022.47 84.512 302911.77 1950934.24 100.0How it works:
- The CTE has one row per month of 2024.
SUM(revenue) OVER (ORDER BY month)adds all months up to the current one. Months are unique, so the default frame has no ties.SUM(revenue) OVER ()has noORDER BYand 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”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.
channel month orders changeonline 2024-10 317 46online 2024-11 554 237online 2024-12 628 74store 2024-10 358 13store 2024-11 464 106store 2024-12 609 145show(""" 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) == 6assert all(row[3] is not None for row in rows)channel month orders changeonline 2024-10 317 46online 2024-11 554 237online 2024-12 628 74store 2024-10 358 13store 2024-11 464 106store 2024-12 609 145How it works:
monthlyhas one row per channel and month: 2 × 24 = 48 rows.PARTITION BY channelruns a separateLAGfor each channel, so the online October looks back to the online September.- The outer
WHEREfilters 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”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)region avg_store_revenueEast 181588.36South 160755.0North 159243.14West 148724.91region avg_store_revenueEast 181588.36South 160755.0North 159243.14West 148724.91cte_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()region avg_store_revenueEast 181588.36South 160755.0North 159243.14West 148724.91How it works:
- The innermost subquery (2024 orders) becomes
orders_2024. The middle one (revenue per store) becomesper_store. The outer query stays as it was. - The CTE version reads top to bottom, in the order the data flows. You can test each step on its own.
- 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”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.
┌─────────┬───────────┬─────────────┐│ 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 │└─────────┴───────────┴─────────────┘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┌─────────┬───────────┬─────────────┐│ 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:
- Both queries first build one row per day, then average per weekday.
- SQLite numbers days 0 (Sunday) to 6. ISO numbers them 1 (Monday) to 7 (Sunday).
iso_dow % 7maps ISO 7 to 0 and leaves 1–6 unchanged, so the two numberings line up. GROUP BY ALLis a DuckDB shortcut that groups by every non-aggregated column. Saturday is the peak and Tuesday the low.- 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.46and.47. One decimal is stable here. For exact money sums, DuckDB has theDECIMALtype.
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”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.
rows written: 5000 contract customers churn_pct0 month-to-month 1252 17.81 one-year 1024 7.92 two-year 884 3.2customers = 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 compareHint 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()rows written: 5000 contract customers churn_pct0 month-to-month 1252 17.81 one-year 1024 7.92 two-year 884 3.2How it works:
to_sqlcreates the tablecustomersinmemwith one column per DataFrame column and inserts all rows.params=(12,)fills the?placeholder. Change the tenure without touching the SQL text.- 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”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.
customers: 3254approach A rows: 4437approach B rows: 3254approach_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 BHint 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_customersassert rows_a > n_customerscustomers: 3254approach A rows: 4437approach B rows: 3254How it works:
- 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.
- Approach B gives each line of a customer a unique number.
line_id DESCbreaks ties between lines of the same day, so exactly one line per customer gets number 1. - 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).
Challenge
Section titled “Challenge”M30-X01 · 90-day repeat purchase by cohort
Section titled “M30-X01 · 90-day repeat purchase by cohort”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.
cohort customers returned_90d returned_pct2023-Q1 731 394 53.92023-Q2 499 247 49.52023-Q3 335 153 45.72023-Q4 358 159 44.42024-Q1 236 102 43.22024-Q2 303 118 38.92024-Q3 318 121 38.1show(""" 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) == 7assert rows[0][0] == "2023-Q1" and rows[-1][0] == "2024-Q3"assert all(0 <= row[3] <= 100 for row in rows)cohort customers returned_90d returned_pct2023-Q1 731 394 53.92023-Q2 499 247 49.52023-Q3 335 153 45.72023-Q4 358 159 44.42024-Q1 236 102 43.22024-Q2 303 118 38.92024-Q3 318 121 38.1How it works:
firstsfinds 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.- The correlated
EXISTSchecks 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. (month + 2) / 3uses SQLite’s integer division on purpose: months 1–3 give 1, 4–6 give 2, and so on.- 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.
M30-X02 · Products bought together
Section titled “M30-X02 · Products bought together”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).
product_a product_b ordersWireless Earbuds Non-Slip Yoga Mat 56Wireless Earbuds Organic Cotton T-Shirt 55Wireless Earbuds Cotton Bed Sheet Set 53Wireless Earbuds Noise-Cancelling Headphones 52Organic Cotton T-Shirt Non-Slip Yoga Mat 45orders with 2+ lines: 4113show(""" 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) == 5assert all(a[2] >= b[2] for a, b in zip(rows, rows[1:]))product_a product_b ordersWireless Earbuds Non-Slip Yoga Mat 56Wireless Earbuds Organic Cotton T-Shirt 55Wireless Earbuds Cotton Bed Sheet Set 53Wireless Earbuds Noise-Cancelling Headphones 52Organic Cotton T-Shirt Non-Slip Yoga Mat 45orders with 2+ lines: 4113How it works:
- The self-join pairs every two lines of the same order. An order with 3 lines gives 3 pairs.
o1.product_id < o2.product_idkeeps each pair once, in one fixed order, and drops a line paired with itself.- Two more joins add the names.
GROUP BYthe two ids counts the orders per pair. - 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”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.
┌─────────┬──────────────┬─────────┬──────────────┬──────────────┐│ 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 │└─────────┴──────────────┴─────────┴──────────────┴──────────────┘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) == 297assert all(row[1] == row[2] for row in rows)assert all(row[3] == 0 for row in rows)┌─────────┬──────────────┬─────────┬──────────────┬──────────────┐│ 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:
union_by_name = truereads the six files as one table, although the April file has its columns in a different order.- The left join keeps every report line. The match uses two keys, because
order_idalone is not unique in the sales data. - 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.
ANY_VALUE(t.month_revenue)takes the month total, which is the same on every row of the group.GROUP BY 1groups by the first column of theSELECT.
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”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".
category lines revenue0 Electronics 355 149266.091 Home 229 54659.122 Sports 144 25150.59 store_id lines revenue0 S09 9 2797.881 S07 17 2613.58ValueError: group_by must be one of ['category', 'channel', 'region', 'store_id']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 category lines revenue0 Electronics 355 149266.091 Home 229 54659.122 Sports 144 25150.59 store_id lines revenue0 S09 9 2797.881 S07 17 2613.58ValueError: group_by must be one of ['category', 'channel', 'region', 'store_id']How it works:
- The allowlist check runs first. A name that is not a key of
GROUP_COLUMNSnever reaches the SQL text. - The f-string inserts only a column name from the dict, written by you. The dates and the limit go through
?placeholders, in order. - Both joins are always present, so each allowed column exists. The joins are on primary keys, so they cannot change the line counts.
- 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).
M30-X05 · Flag unusual revenue days
Section titled “M30-X05 · Flag unusual revenue days”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.
┌────────────┬──────────┬──────────┬───────────────┬────────┐│ 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 │└────────────┴──────────┴──────────┴───────────────┴────────┘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) == 4assert str(rows[0][0]) == "2024-11-29"assert all(row[4] > 3 for row in rows)┌────────────┬──────────┬──────────┬───────────────┬────────┐│ 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:
dailyhas 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.- 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. - 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.
- 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.