Window Functions
Lesson opener
In one line: ROW_NUMBER, RANK, running totals with OVER().
Why it matters: ORDER BY alone doesn't give you a rank column you can filter or join on - you need a numbered row per customer.
Before this lesson: CTE & Views
Before you start
| Resource | Link |
|---|---|
| Previous | CTE & Views |
| Next | Constraints & transactions |
What you will learn
ROW_NUMBER, RANK, running totals with OVER().
ROW_NUMBER
[Rank every customer by revenue]
WHY: ORDER BY alone doesn't give you a rank column you can filter or join on — you need a numbered row per customer.
WHEN: You're picking the top 50 customers by revenue and need a stable rank column for a export.
SELECT customer_id, total_revenue,
ROW_NUMBER() OVER (ORDER BY total_revenue DESC) AS rn
FROM customers;Breaking it down:
ROW_NUMBER()→ assigns 1, 2, 3… with no tie logic — each row gets a unique numberOVER (ORDER BY total_revenue DESC)→ window [set of rows]: order the whole table by revenue high→low before numberingAS rn→ rank column in the result
Use this when: You need a sequential rank across the full table (top N, row labels).
PARTITION BY
[Rank within each segment]
WHY: Company-wide rank hides who's #1 in Gold vs #1 in Bronze — partition restarts the race per group.
WHEN: Segment managers each want "top customers in my segment" on one query.
SELECT customer_id, segment, total_revenue,
RANK() OVER (PARTITION BY segment ORDER BY total_revenue DESC) AS seg_rank
FROM customers;Breaking it down:
PARTITION BY segment→ separate window per segment — ranks restart in each bucketRANK()→ ties get the same rank; next rank skips (1, 1, 3…) — unlike ROW_NUMBERORDER BY total_revenue DESC→ richest first within each partition
Use this when: Leaderboards or top-N within category (segment, region, month).
Running total on sales
[Cumulative monthly revenue]
WHY: Monthly totals show each month alone — a running total shows "how much have we banked so far this series?"
WHEN: Finance tracks cumulative revenue through the year on a line chart.
SELECT month, revenue,
SUM(revenue) OVER (ORDER BY month ROWS UNBOUNDED PRECEDING) AS running_rev
FROM (
SELECT month, SUM(revenue) AS revenue
FROM sales
GROUP BY month
) m;Breaking it down:
- Inner subquery → one row per month with
SUM(revenue)— monthly grain first SUM(revenue) OVER (ORDER BY month ROWS UNBOUNDED PRECEDING)→ add current month plus all earlier months in sort orderROWS UNBOUNDED PRECEDING→ include every prior row in the window, not just the current row
Use this when: You need a running/cumulative metric over time without exporting to Excel.
Next
Power BI for visuals on SQL views.
Essential commands
| Command / action | What it does |
|---|---|
ROW_NUMBER() OVER (ORDER BY col) | Sequential rank without ties logic. |
RANK() / DENSE_RANK() OVER (...) | Ranking with tie handling. |
PARTITION BY col | Restart window per group. |
SUM(col) OVER (ORDER BY ... ROWS ...) | Running total within partition. |
Practice
Before each query, name the three SQL beats — Source → Pattern → Result (SQL translation of Input → Logic → Output — see sql2). Window queries keep every Source row; Pattern is … OVER (…) and Result adds a calculated column (rank, running total) without collapsing groups.
Do this now:
ROW_NUMBERrank of customers by revenue (worked model below).RANK(orROW_NUMBER) withPARTITION BY segment.- Running monthly revenue with
SUM() OVER (…). - Save
10_windows.sql.
Example framing for task 1:
-- Source: customers (customer_id, total_revenue)
-- Pattern: ROW_NUMBER() OVER (ORDER BY …)
-- Result: one row per customer plus unique rank rn (richest first)
SELECT customer_id, total_revenue,
ROW_NUMBER() OVER (ORDER BY total_revenue DESC) AS rn
FROM customers;Framing prompts for the rest (fill these blanks in your .sql comments before writing each query):
- Source: ___
Pattern: ___
Result: ___
- Source: ___
Pattern: ___
Result: ___
Checklist
- [ ] Window query runs in MySQL 8+
- [ ] PARTITION BY used
- [ ] Ready for Power BI track