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.

35 min 3 practice tasks
SQL Window Function | How to write SQL Query using RANK, DENSE RANK, LEAD/LAG | SQL Queries Tutorial by techTFQ on YouTube

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 channel splits rows into independent groups, like GROUP BY but without collapsing them. Leave it out and the whole result is one window.
  • ORDER BY inside OVER sets the order within each window. It matters for rankings, running totals and LAG, and is independent of the query’s final ORDER 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_NUMBER always gives 1, 2, 3, … with no ties (add a tie-breaker to the window’s ORDER BY so it’s repeatable).
  • RANK gives ties the same rank, then skips (2, 2, 2, 2, 6), like a sports leaderboard.
  • DENSE_RANK gives 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, LAG and LEAD work 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.

1

Best campaign in each channel

For 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?
  1. Number the campaigns inside each channel: ROW_NUMBER() OVER (PARTITION BY channel ORDER BY revenue DESC).
  2. You can't filter a window function in the same query's WHERE. Put it in a second CTE, then keep rn = 1.
SQL · SQLite
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)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
2

Running total of March spend

Finance 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?
  1. First get one row per day (a CTE with GROUP BY date), then add the running total on top.
  2. A running total is SUM(spend) OVER (ORDER BY date): the sum of all rows up to the current one.
SQL · SQLite
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)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
3

Month over month by channel

For 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?
  1. LAG(revenue) returns the value from the previous row of the window.
  2. Restart for every channel and step through months in order: OVER (PARTITION BY channel ORDER BY month).
SQL · SQLite
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)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue