Section 4 · Lesson 2
Window functions: ranking, running totals and LAG
Rank rows within groups, build running totals and compare each period with the previous one, all without collapsing your rows.
GROUP BY answers “what’s the total per channel?” but throws away the individual rows. Often
you want both: every campaign and how it ranks within its channel; every day and the
month-to-date total. Window functions compute values across a set of related rows (the
window) while keeping every row in the result.
The anatomy of a window function
SELECT name, channel, daily_budget,
RANK() OVER (PARTITION BY channel ORDER BY daily_budget DESC) AS budget_rank
FROM campaigns;
- The function (
RANK(),SUM(...),LAG(...)) says what to compute. OVER (...)marks it as a window function.PARTITION BY channelsplits rows into independent groups, likeGROUP BYbut without collapsing them. Leave it out and the whole result is one window.ORDER BYinsideOVERsets the order within each window. It matters for rankings, running totals andLAG, and is independent of the query’s finalORDER BY.
Ranking: ROW_NUMBER, RANK, DENSE_RANK
They differ only in how they treat ties. Ranking campaigns by budget (four share 1,400 USD):
| campaign | daily_budget | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|---|
| BlueHarbor Conversions Search 38 | 1500 | 1 | 1 | 1 |
| Coastal Conversions Search 12 | 1400 | 2 | 2 | 2 |
| Cobalt Awareness Social 30 | 1400 | 3 | 2 | 2 |
| Quantum Conversions Video 11 | 1400 | 4 | 2 | 2 |
| Summit Conversions Display 13 | 1400 | 5 | 2 | 2 |
| Quantum Awareness Video 23 | 1350 | 6 | 6 | 3 |
ROW_NUMBERalways gives 1, 2, 3, … with no ties (add a tie-breaker to the window’sORDER BYso it’s repeatable).RANKgives ties the same rank, then skips (2, 2, 2, 2, 6), like a sports leaderboard.DENSE_RANKgives ties the same rank without gaps (2, then 3).
Top-N per group
“Best campaign in each channel” is the classic use. Window functions are evaluated after
WHERE, so you can’t filter on them directly. Compute the rank in a CTE, then filter:
WITH ranked AS (
SELECT channel, name, daily_budget,
ROW_NUMBER() OVER (PARTITION BY channel ORDER BY daily_budget DESC, name) AS rn
FROM campaigns
)
SELECT channel, name, daily_budget
FROM ranked
WHERE rn <= 2; -- top 2 per channel
Running totals with SUM() OVER
Add ORDER BY inside the window and SUM becomes cumulative: each row gets the total of all
rows up to and including itself.
SELECT date, spend,
SUM(spend) OVER (PARTITION BY campaign_id ORDER BY date) AS spend_to_date
FROM daily_stats
WHERE campaign_id = 130;
Without ORDER BY, SUM(spend) OVER (PARTITION BY campaign_id) puts the campaign’s grand total
on every row, which is handy for “share of total” calculations
(spend / SUM(spend) OVER (...)).
Looking back with LAG (and ahead with LEAD)
LAG(column) returns the value from the previous row of the window; LEAD(column) from the
next one. That makes period-over-period comparisons a one-liner:
WITH monthly AS (
SELECT strftime('%Y-%m', date) AS month, SUM(spend) AS spend
FROM daily_stats
GROUP BY month
)
SELECT month, spend,
LAG(spend) OVER (ORDER BY month) AS prev_spend,
spend - LAG(spend) OVER (ORDER BY month) AS change
FROM monthly;
The first row has no previous row, so LAG returns NULL there. LAG(spend, 1, 0) would
return 0 instead, but NULL is usually more honest: there’s no prior month to compare with.
Windows over grouped results
You can apply a window to the output of a GROUP BY in the same query, e.g.
SUM(SUM(spend)) OVER (ORDER BY date), but a CTE that groups first and a second step that adds
the window is far easier to read. That’s the pattern used in the tasks.
About the video: its examples use a different sample table, but
ROW_NUMBER,RANK,DENSE_RANK,LAGandLEADwork identically in SQLite (version 3.25 or newer, which the sandbox uses). Running totals aren’t covered in the video, so study that section above.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Best campaign in each channel
DoneFor each channel, find the single campaign with the highest total revenue (from daily_stats). Return channel, the campaign name and its total revenue rounded to 2 decimals: one row per channel, sorted by channel A to Z.
Need a hint?
- Number the campaigns inside each channel:
ROW_NUMBER() OVER (PARTITION BY channel ORDER BY revenue DESC). - You can't filter a window function in the same query's
WHERE. Put it in a second CTE, then keeprn = 1.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
WITH campaign_revenue AS (
SELECT c.channel, c.name, SUM(d.revenue) AS revenue
FROM daily_stats AS d
JOIN campaigns AS c ON c.id = d.campaign_id
GROUP BY c.id, c.channel, c.name
)
SELECT channel, name, ROUND(revenue, 2) AS revenue
FROM campaign_revenue
ORDER BY channel;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Running total of March spend
DoneFinance tracks spend against the monthly budget day by day. For each date in March 2026, return the date, the total spend across all campaigns that day, and the running total of spend from March 1 up to and including that day. Round both amounts to 2 decimals and sort by date.
Need a hint?
- First get one row per day (a CTE with
GROUP BY date), then add the running total on top. - A running total is
SUM(spend) OVER (ORDER BY date): the sum of all rows up to the current one.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT date, ROUND(SUM(spend), 2) AS daily_spend
FROM daily_stats
WHERE date BETWEEN '2026-03-01' AND '2026-03-31'
GROUP BY date
ORDER BY date;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Month over month by channel
DoneFor each channel and month, return four columns: channel, the month as YYYY-MM, total revenue that month (from daily_stats), and the previous month's revenue for the same channel (NULL for the channel's first month). Round both revenue columns to 2 decimals. Sort by channel, then month.
Need a hint?
LAG(revenue)returns the value from the previous row of the window.- Restart for every channel and step through months in order:
OVER (PARTITION BY channel ORDER BY month).
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
WITH monthly AS (
SELECT c.channel,
strftime('%Y-%m', d.date) AS month,
SUM(d.revenue) AS revenue
FROM daily_stats AS d
JOIN campaigns AS c ON c.id = d.campaign_id
GROUP BY c.channel, month
)
SELECT channel, month, ROUND(revenue, 2) AS revenue
FROM monthly
ORDER BY channel, month;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)