In the pandas lesson, head(1) showed only one winner for Manchester, though the week of 5 October there is a tie. SQL has the right tool for that, and for other questions about many rows at once, not just reading and changing one row (CRUD). That kind of SQL is the everyday work of data engineering. Take a school's grade book. GROUP BY folds every student into one row per class: "class 7A's average". A window function leaves each student in their own row and writes next to it "rank 2 in class 7A". Both are worked out per class; the difference is that one folds the rows and the other doesn't.
Window functions: working things out without folding rows
A window function is written with OVER (...):
PARTITION BYsplits the rows into groups (windows), likeGROUP BY, but the rows aren't folded.ORDER BYinsideOVERorders the rows in each window, for rankings and running sums.
The functions include ROW_NUMBER() (sequence numbers 1, 2, 3), RANK() (a rank where ties get the same number), SUM(...) OVER (...) (a running sum) and LAG(...) (the previous row's value). Because the rows don't disappear, running totals and rankings work without GROUP BY. Every query here runs in SQLite (the same as the Lab and the Playground) on Bookshop's data.
ROW_NUMBER: dropping doubled lines
SELECT id, order_id, book_id, qty,
ROW_NUMBER() OVER (PARTITION BY order_id, book_id ORDER BY id) AS rn
FROM order_items
WHERE order_id IN (5, 6);
| id | order_id | book_id | qty | rn |
|---|---|---|---|---|
| 7 | 5 | 2 | 1 | 1 |
| 8 | 6 | 2 | 2 | 1 |
| 9 | 6 | 2 | 2 | 2 |
PARTITION BY order_id, book_idmakes one window per order and book pair. Order 6 with This Earth of Mankind has two rows.ORDER BY iddecides who's number 1: the smallest id, the one saved first.- Rows with
rn = 1are kept;rn = 2is the doubled line. UnlikeDISTINCTin the first lesson,ROW_NUMBERstill works when the twin rows differ in another column (such asid, or the time they were loaded), and you choose which one stays.
Bucketing by week
The owner's question needs dates rounded down to the start of the week. Each database writes it differently:
| Database | The Monday starting the week of created_at |
|---|---|
| SQLite | date(created_at, 'weekday 0', '-6 days') |
| MySQL | DATE_SUB(DATE(created_at), INTERVAL WEEKDAY(created_at) DAY) |
| PostgreSQL, DuckDB | date_trunc('week', created_at) |
| BigQuery | DATE_TRUNC(DATE(created_at), WEEK(MONDAY)); plain WEEK starts on Sunday |
In SQLite, 'weekday 0' moves forward to the nearest Sunday (or stays, if it's already Sunday), then '-6 days' goes back to its Monday. Watch out for Sundays: Maya's order 2026-10-04 20:30:00 falls on a Sunday. With weeks starting Monday, it belongs to the week of 28 September; with weeks starting Sunday, it belongs to the week of 4 October, and the answer changes. Agree on the start of the week with the owner first.
CTE: the owner's question, step by step
A CTE (Common Table Expression) is WITH name AS (SELECT ...): a named step that only lives while that query runs. Several CTEs are separated by commas, and each step can read the steps before it. A query that used to be nested subqueries can be read top to bottom, and each step can be checked on its own with SELECT * FROM step_name.
WITH clean AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id, book_id ORDER BY id) AS rn
FROM order_items
),
sales AS (
SELECT date(o.created_at, 'weekday 0', '-6 days') AS week,
COALESCE(c.city, 'Unknown') AS city,
b.title AS title,
i.qty
FROM clean i
JOIN orders o ON o.id = i.order_id
JOIN customers c ON c.id = o.customer_id
JOIN books b ON b.id = i.book_id
WHERE i.rn = 1
),
per_title AS (
SELECT week, city, title, SUM(qty) AS sold
FROM sales
GROUP BY week, city, title
),
ranking AS (
SELECT *, RANK() OVER (PARTITION BY week, city ORDER BY sold DESC) AS position
FROM per_title
)
SELECT week, city, title, sold, position
FROM ranking
WHERE position = 1
ORDER BY week, city, title;
The data has 2 weeks and 4 cities, so 8 groups. Before you look at the result, guess: how many rows come out, 8 or 9?
| week | city | title | sold | position |
|---|---|---|---|---|
| 2026-09-28 | Bristol | This Earth of Mankind | 2 | 1 |
| 2026-09-28 | London | The Rainbow Troops | 3 | 1 |
| 2026-09-28 | Manchester | Beauty Is a Wound | 2 | 1 |
| 2026-09-28 | Unknown | The Rainbow Troops | 1 | 1 |
| 2026-10-05 | Bristol | The Dancer | 2 | 1 |
| 2026-10-05 | London | Beauty Is a Wound | 2 | 1 |
| 2026-10-05 | Manchester | The Dancer | 1 | 1 |
| 2026-10-05 | Manchester | The Rainbow Troops | 1 | 1 |
| 2026-10-05 | Unknown | This Earth of Mankind | 1 | 1 |
cleannumbers the twin rows, andsaleskeeps onlyrn = 1and gives aNULLcity a name.per_titlesums per week, city and title.rankinggives each a position without folding rows.WHERE position = 1sits in the outer query. Window functions are worked out afterWHERE, so they can't be filtered in the same query'sWHERE; that's what therankingstep is for.
The result has 9 rows, because Manchester in the week of 5 October is a tie: The Dancer and The Rainbow Troops both at 1, and RANK() gives both position 1. ROW_NUMBER() would give 8 rows, picking one with no guarantee which. DENSE_RANK() matches RANK() for the winners; the difference is below them: after two tied winners, RANK goes on to 3, DENSE_RANK to 2.
Running total
Daily revenue and its running sum, from the cleaned data:
WITH daily AS (
SELECT date(o.created_at) AS order_date, SUM(oi.qty * b.price) AS revenue
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id, book_id ORDER BY id) AS rn FROM order_items) oi
JOIN orders o ON o.id = oi.order_id
JOIN books b ON b.id = oi.book_id
WHERE oi.rn = 1
GROUP BY order_date
)
SELECT order_date, revenue,
SUM(revenue) OVER (ORDER BY order_date) AS running_total
FROM daily
ORDER BY order_date;
Its first four rows: 2026-09-28 | 65 | 65, 2026-09-29 | 44 | 109, 2026-09-30 | 55 | 164, 2026-10-01 | 75 | 239. The last row, 2026-10-09, has a running_total of 444: the total clean revenue. SUM(...) OVER (ORDER BY order_date) adds up from the first row to that row.
ROLLUP and GROUPING SETS
ROLLUP adds subtotal and total rows to a GROUP BY result. GROUP BY ROLLUP (city) is the same as GROUP BY GROUPING SETS ((city), ()): one row per city, plus one total row whose city is NULL. PostgreSQL, DuckDB, BigQuery and Snowflake write it that way; MySQL writes GROUP BY city WITH ROLLUP.
SQLite has no ROLLUP at all. GROUP BY ROLLUP (c.city) gets no such function: ROLLUP, and WITH ROLLUP gets near "WITH": syntax error. Instead, use UNION ALL with a total query:
WITH sales AS (
SELECT COALESCE(c.city, 'Unknown') AS city, i.qty
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id, book_id ORDER BY id) AS rn FROM order_items) i
JOIN orders o ON o.id = i.order_id
JOIN customers c ON c.id = o.customer_id
WHERE i.rn = 1
)
SELECT city, SUM(qty) AS sold FROM sales GROUP BY city
UNION ALL
SELECT 'ALL CITIES', SUM(qty) FROM sales;
The result is Bristol 5, London 9, Manchester 5, Unknown 2, then ALL CITIES 21. DuckDB with ROLLUP gives the same numbers, with NULL where ALL CITIES is.
NULL means "unknown"
NULL isn't an empty value; it means "not known". Any comparison with NULL is unknown too, and WHERE only lets through what's true. On the 19 order_items rows joined to their customers:
| Expression | Result |
|---|---|
COUNT(*) |
19 |
COUNT(c.city) |
17: COUNT(column) doesn't count NULL |
rows with c.city <> 'London' |
9, not 11: Maya's 2 rows are thrown out too |
rows with c.city IS NULL |
2: checking for NULL needs IS NULL, not = NULL |
COALESCE(c.city, 'Unknown') replaces NULL with a value you choose, as in the sales CTE. GROUP BY gathers every NULL into one group.
⚠️ Rankings, NULL and where a week starts
- Filtering a window function in the same
WHERE.WHERE RANK() OVER (...) = 1is refused. Work it out in a CTE, filter in the outer query. ROW_NUMBERfor finding the winner. Ties get hidden. UseRANKwhen every tied row must show.<>orNOT INon a column that can beNULL. Rows vanish silently.COALESCEfirst, or addOR column IS NULL.- Different starts of the week. SQLite, MySQL and PostgreSQL above start on Monday; BigQuery's
WEEKstarts on Sunday. Sunday orders change weeks.
TL;DR: Window functions (... OVER (PARTITION BY ... ORDER BY ...)) work things out per group without folding rows: ROW_NUMBER() to drop doubled lines (rn = 1), RANK() for a ranking that shows ties, SUM() OVER (ORDER BY order_date) for a running total. A CTE (WITH name AS (...)) breaks a long query into named steps that read top to bottom and can be checked one by one; window functions are filtered in the outer query. Dates round down to Monday with date(created_at, 'weekday 0', '-6 days') in SQLite or date_trunc('week', ...) in PostgreSQL and DuckDB. SQLite has no ROLLUP; use UNION ALL with a total row. NULL means unknown: <> 'London' drops NULL rows, and COUNT(column) skips them. The owner's answer: 9 rows, because Manchester ties in the week of 5 October.
⚡ Window functions don't fold rows
Meaning: GROUP BY folds every row into one per group. A window function, written with OVER (PARTITION BY ... ORDER BY ...), works things out per group while every row stays.
⚡ ROW_NUMBER drops doubled lines
Write:
SELECT id, order_id, book_id, qty,
ROW_NUMBER() OVER (PARTITION BY order_id, book_id ORDER BY id) AS rn
FROM order_items
WHERE order_id IN (5, 6);
Meaning: Item 8 gets rn = 1, its twin item 9 gets rn = 2. Keep only the rn = 1 rows.
⚡ CTE: named steps
Meaning: WITH name AS (SELECT ...) breaks a long query into named steps that read top to bottom. Each step can be checked on its own with SELECT * FROM step_name, and window functions are filtered in the outer query.
⚡ RANK shows ties
Guess first: 2 weeks times 4 cities is 8 groups. How many rows does the winner per week and city with RANK() return, 8 or 9?
The answer is 9. Manchester in the week of 5 October is a tie: The Dancer and The Rainbow Troops both at 1, and RANK() gives both position 1. ROW_NUMBER() gives only 8 rows.
Meaning: Use RANK when every tied row must show.