Semester 1 · Week 06
SQL for data science
- Ch 8 SQL for Data Science
Chapter 8: SQL for data science
From "I can write a WHERE clause" to "I can answer the business question".
Notes · slide 2
Time: 50 minutes for one chapter. About 25 on the tools, 15 on the worked example, and 10 on the mental model and checks.
Say: Most of you can already write SELECT * FROM orders WHERE status = 'active'. That retrieves records. Tonight is SQL that answers questions: which customers grew their spend, what share of revenue comes from the top tenth.
Key line: treat SQL as asking questions of sets of rows, not fetching single ones.
Next: the two kinds of SQL.
Operational SQL and analytical SQL
- Operational SQL looks things up.
- Analytical SQL answers questions over many rows: totals, ranks, growth, cohorts.
- SQL is declarative. You describe the result. The query planner decides how.
- The shift that unlocks it: think in aggregations over groups.
Notes · slide 3
Say: Operational SQL looks up a record. Analytical SQL summarises, ranks, and compares over many rows. Many capable engineers stall the first time they get a warehouse table and a business question instead of a lookup.
Say: SQL is declarative. You describe the result. The planner chooses how to get it.
Key line: almost every analytical question has the shape "for each group, what is the aggregate of a value?"
Ask: "Rephrase 'which product sells best?' in that shape." Listen for: for each product, the sum of sales.
Next: GROUP BY.
GROUP BY and HAVING
SELECT category,
SUM(amount) AS revenue,
AVG(amount) AS avg_order
FROM orders
WHERE status = 'completed'
GROUP BY category
HAVING SUM(amount) > 100000;GROUP BYcollapses each group to one row.HAVINGfilters after aggregating.WHEREfilters before.
Notes · slide 4
Say: GROUP BY splits rows into groups that share a value and collapses each group to one summary row. Here: revenue and average order per category, completed orders only.
Say: WHERE filters rows before they enter a group. HAVING filters groups after the aggregate exists. That's why HAVING can use SUM and WHERE can't.
Say: Some databases reject a SELECT alias inside HAVING. Repeating the aggregate works everywhere.
Ask: "Categories with over 100,000 in revenue, counting only completed orders. Which condition goes where?" Listen for: status in WHERE, the sum in HAVING.
Next: keeping long queries readable.
CTEs: name each step
WITH completed AS (
SELECT * FROM orders WHERE status = 'completed'
),
customer_value AS (
SELECT customer_id, SUM(amount) AS ltv
FROM completed GROUP BY customer_id
)
SELECT * FROM customer_value ORDER BY ltv DESC;For readability, not speed. Each CTE should do one thing.
Notes · slide 5
Say: A CTE is a named subquery at the top, introduced with WITH. It's for readability, not speed. Build a query as named steps, the way you'd split a long function into small ones.
Say: Give each CTE one job and a name that says what it is. Then the final SELECT reads almost like English.
Say: Some engines re-run a CTE each time it's referenced. If it's heavy and reused, check the plan or use a temp table.
Next: the tool that changes what SQL can answer.
Window functions
A window function keeps every row and adds a computed column.
SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date)GROUP BY: one row per group.- Window function: every row, with the group's value alongside.
Notes · slide 6
Do: draw a small orders table on the board. Box each customer's rows: that's the partition. Number them by date: that's the ordering. Write the running total beside each row.
Say: A window function computes across related rows but keeps every row. GROUP BY gives one row per group. A window gives every row, with the group's value beside it.
Key line: a window function is GROUP BY that keeps your rows.
Ask: "Each order alongside that customer's total spend. Which do you use?" Listen for: a window, SUM OVER PARTITION BY customer.
Next: the three families.
The three families
| Family | Functions | Use for |
|---|---|---|
| Ranking | ROW_NUMBER, RANK, DENSE_RANK, NTILE |
Top-N per group, quartiles |
| Offset | LAG, LEAD |
Period-over-period change |
| Aggregate | SUM, AVG, COUNT with OVER |
Running totals, shares of a total |
RANK gives 1, 1, 3. DENSE_RANK gives 1, 1, 2. ROW_NUMBER never ties.
Notes · slide 7
Say: Ranking: top N per group. ROW_NUMBER never ties. RANK gives 1, 1, 3. DENSE_RANK gives 1, 1, 2. Offset: LAG looks back, LEAD looks forward, within the partition. That's how you get change since last month. Aggregate: SUM or AVG with OVER gives running totals and shares of a total. An empty OVER() attaches the grand total to every row.
Say: LAG on the first row returns NULL, not zero. Wrap it in COALESCE if you need a zero.
Ask: "Top 3 products per category, with ties allowed?" Listen for: RANK or DENSE_RANK, filtered to 3 or under.
Next: joins.
Joins for analysis
| Join | Keeps |
|---|---|
INNER |
Rows matching in both |
LEFT |
Every left row, NULL where no match |
FULL OUTER |
Every row from both sides |
LEFT JOIN dominates: enrich a fact table (orders) with dimension data (customers, products) without losing facts.
Notes · slide 8
Say: INNER keeps matches only. LEFT keeps every left row, with NULLs where there's no match. FULL OUTER keeps everything from both sides.
Say: In analysis, LEFT JOIN dominates. Start from a fact table, such as orders or events, and add attributes from dimension tables, such as customers or products. You keep every fact even when a dimension row is missing.
Key line: count rows before and after every join. If the count grows, a key isn't unique.
Next: when the data gets big.
SQL at scale
The same query that runs on a thousand rows can fail on a billion.
- Filter early.
- Select only the columns you need. Columnar stores reward this.
- Know what drives the join. Check the plan with
EXPLAIN. - Watch for a full table scan where an index scan was expected.
Notes · slide 9
Say: The same query on a billion rows can take minutes or fail. The SQL didn't change. The amount of data it touches did.
Say: Filter early, so joins see fewer rows. Select only the columns you need: columnar warehouses read each column separately. Don't wrap a filtered column in a function. YEAR(order_date) = 2023 can't use an index. A date range can.
Say: Use EXPLAIN ANALYZE to see the real plan and timings. On Athena, which bills per byte scanned, these habits save money too.
Next: SQL or pandas.
SQL or pandas?
- SQL when the data lives in a database, the query joins several tables, or the data won't fit in memory.
- pandas for in-memory work, reshaping, and plotting.
- DuckDB runs SQL directly on DataFrames. You don't have to pick one.
Notes · slide 10
Say: Not a rivalry. SQL when the data lives in a database, when you join many tables, or when it won't fit in memory. pandas for in-memory work, custom feature engineering, and plotting.
Say: Strong data scientists use both as stages. Aggregate in the database, then finish features in Python. A ten-table join written as pandas merges is slow and hard to read.
Say: DuckDB runs SQL directly on DataFrames, so you can mix them in one notebook. The lab uses it.
Next: the worked example.
Worked example: an e-commerce database
DuckDB, in memory: 200 customers, 50 products, 3,000 orders.
| Category | Revenue | Average order |
|---|---|---|
| Sports | $630,003 | $833 |
| Clothing | $553,493 | $1,035 |
| Home | $408,763 | |
| Electronics | $344,965 | |
| Books | $179,920 |
Total revenue and average order value answer different questions. Pull both.
Notes · slide 11
Say: A DuckDB database in memory: 200 customers, 50 products, 3,000 orders. Only completed orders count as revenue. Returned and pending haven't landed.
Say: Sports leads on total revenue. Clothing has fewer orders but the highest average order, $1,035 against $833. A total-revenue chart alone would hide that.
Key line: total and average answer different business questions. The same GROUP BY gives both, so pull both.
Lab: the common mistake is counting cancellations as sales. Check the status filter first.
Next: a question GROUP BY can't answer.
Worked example: the Pareto question
What share of revenue comes from the top customers?
- A running
SUMover customers, ordered by value, divided bySUM(...) OVER (). - 80% of revenue takes 138 of 200 customers.
- Much flatter than the classic 80/20.
Why? The synthetic data draws spend from uniform distributions. Real purchasing is heavy-tailed.
Notes · slide 12
Say: What share of revenue comes from the top customers? A CTE gets each customer's value. A running SUM ordered by value, divided by SUM OVER () for the grand total, gives a cumulative share. One query.
Say: It takes 138 of 200 customers to reach 80% of revenue. Much flatter than 80/20.
Ask: "Why?" Listen for: the synthetic spend comes from uniform draws. Real purchasing is heavy-tailed. That's Chapter 3's distribution thinking.
Next: a cohort question.
Worked example: a 90-day cohort
Of customers whose first order was in Q1 2022, how many ordered again within 90 days?
- 128 of 156: 82.1%.
- Suspiciously high. Orders were spread at random over two years.
A correct query on unrealistic data still gives a meaningless number.
Notes · slide 13
Say: Of customers whose first order was in Q1 2022, how many ordered again within 90 days? 128 of 156: 82.1%.
Say: That's suspiciously high for real e-commerce. The generator scattered orders at random over two years. Any customer with a few orders is likely to have one in the next 90 days by chance.
Key line: the query being right is necessary, not sufficient. Always ask how the data was made.
Next: the chapter in one idea.
Mental model
SQL asks questions of sets.
- Partition the rows into groups.
- Optionally order within each group.
- Then either collapse each group (
GROUP BY) or attach a value to every row (a window).
Window functions are GROUP BY that keeps your rows.
Notes · slide 14
Say: SQL asks questions of sets. Partition the rows into groups. Optionally order within each group. Then collapse each group with GROUP BY, or attach a value to every row with a window.
Key line: window functions are GROUP BY that keeps your rows.
Next: check yourself.
Check yourself
- You need each customer's first order date on every order row.
GROUP BYor window? - Why does
HAVINGexist whenWHEREdoes? - Write the expression for month-over-month revenue change.
- A join turns 3,000 orders into 4,200 rows. What went wrong?
Notes · slide 15
Do: pairs, three minutes, then take answers. Ask one pair to write question 3 on the board.
Answers: 1. A window: MIN(order_date) OVER (PARTITION BY customer_id). 2. WHERE runs before aggregation, so it can't filter on a SUM. 3. revenue − LAG(revenue) OVER (ORDER BY month). 4. The dimension table has duplicate keys, so each order matched more than one row.
Lab: window functions are the hard part. Draw the partition and ordering again for any pair that's stuck.
This week
- Read Chapter 8: SQL for Data Science.
- Take the Chapter 8 quiz.
- Run the notebooks: Chapter 8 (opens in a new tab).
- Optional: the further reading for week 6.
Slide 1 of 16: SQL for data science
Keys: → or Space next · ← back · Home/End · F full screen · N notes. Swipe on touch screens. "Save as PDF" opens the print dialog with one slide per page: choose "Save as PDF" as the printer. "Print handout" adds the speaker notes, in black on white.