Lesson 218 of 296
Window functions
What you will learn
- What a window function is and how it differs from GROUP BY
- OVER, PARTITION BY and ORDER BY
- ROW_NUMBER, RANK and DENSE_RANK
- Running totals
- LAG and LEAD
- The "top N per group" pattern
On this page
What is a window function?
GROUP BY collapses rows: many orders become one row per customer. A window function calculates across a set of related rows (the window) without collapsing them: every row stays, and gets an extra calculated value.
function() OVER (PARTITION BY ... ORDER BY ...)PARTITION BYsplits rows into groups (like GROUP BY, but rows are kept).ORDER BYinside OVER sets the order within each partition (needed for ranking, running totals and LAG/LEAD).- An empty
OVER ()means the window is the whole result.
Ranking, running totals and change
WITH order_totals AS (
SELECT o.id, o.customer_id, o.ordered_at,
SUM(oi.quantity * oi.unit_price_pence) AS total_pence
FROM orders o JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'paid'
GROUP BY o.id
)
SELECT customer_id, id AS order_id, ordered_at, total_pence,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ordered_at) AS nth_order,
SUM(total_pence) OVER (PARTITION BY customer_id ORDER BY ordered_at) AS running_total,
total_pence - LAG(total_pence) OVER (PARTITION BY customer_id ORDER BY ordered_at) AS change_from_previous
FROM order_totals
ORDER BY customer_id, ordered_at;| customer_id | order_id | ordered_at | total_pence | nth_order | running_total | change_from_previous |
|---|---|---|---|---|---|---|
| 1 | 101 | 2026-06-01 | 2248 | 1 | 2248 | NULL |
| 1 | 102 | 2026-06-15 | 2999 | 2 | 5247 | 751 |
| 3 | 104 | 2026-07-02 | 3399 | 1 | 3399 | NULL |
| 3 | 106 | 2026-08-01 | 3898 | 2 | 7297 | 499 |
ROW_NUMBER()numbers rows 1, 2, 3 within each customer.SUM(...) OVER (... ORDER BY ...)gives a running total (the sum from the first row up to the current one).LAG(x)reads the value from the previous row in the partition (NULL for the first);LEAD(x)reads the next row. Perfect for "change since last month" or "time between orders".
ROW_NUMBER vs RANK vs DENSE_RANK
The difference shows with ties:
SELECT score,
ROW_NUMBER() OVER (ORDER BY score DESC) AS row_number,
RANK() OVER (ORDER BY score DESC) AS rank,
DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank
FROM (VALUES (90), (85), (85), (70)) AS t(score);| score | row_number | rank | dense_rank |
|---|---|---|---|
| 90 | 1 | 1 | 1 |
| 85 | 2 | 2 | 2 |
| 85 | 3 | 2 | 2 |
| 70 | 4 | 4 | 3 |
| Function | Ties | Gaps after ties |
|---|---|---|
ROW_NUMBER | Different numbers (arbitrary order between ties) | n/a |
RANK | Same number | Yes (2, 2, then 4) |
DENSE_RANK | Same number | No (2, 2, then 3) |
"Find the second-highest salary" is classic: use DENSE_RANK() = 2, so ties at the top do not break the answer.
Percentages of a total
SELECT name, category, price_pence,
RANK() OVER (PARTITION BY category ORDER BY price_pence DESC) AS rank_in_category,
ROUND(100.0 * price_pence / SUM(price_pence) OVER (), 1) AS pct_of_all
FROM products
ORDER BY category, rank_in_category;| name | category | price_pence | rank_in_category | pct_of_all |
|---|---|---|---|---|
| Desk Lamp | Home | 2999 | 1 | 33.0 |
| Kettle | Kitchen | 3499 | 1 | 38.5 |
| Mug | Kitchen | 899 | 2 | 9.9 |
| Pen Set | Stationery | 1250 | 1 | 13.7 |
| Notebook | Stationery | 450 | 2 | 4.9 |
100.0 (not 100) makes the division decimal; integer division in SQL drops the fraction (7 / 2 is 3).
Top N per group
"The latest order for each customer" (or the top 3 products per category) is one of the most asked SQL questions. Window functions run after WHERE, so you cannot filter on them directly. Wrap the query and filter outside:
SELECT * FROM (
SELECT c.name, o.id AS order_id, o.ordered_at,
ROW_NUMBER() OVER (PARTITION BY o.customer_id ORDER BY o.ordered_at DESC) AS rn
FROM orders o JOIN customers c ON c.id = o.customer_id
) latest
WHERE rn = 1
ORDER BY name;| name | order_id | ordered_at | rn |
|---|---|---|---|
| Aisha Khan | 102 | 2026-06-15 | 1 |
| Ben Smith | 103 | 2026-06-20 | 1 |
| Chen Li | 106 | 2026-08-01 | 1 |
| Dara Patel | 105 | 2026-07-10 | 1 |
Change rn = 1 to rn <= 3 for the top 3. PostgreSQL also has the shortcut SELECT DISTINCT ON (customer_id) ... ORDER BY customer_id, ordered_at DESC for the top 1.
Frames
For moving averages, the frame clause sets which rows around the current one are included: AVG(total) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) gives a 7-day moving average.
How to say it in an interview
"Window functions compute across related rows without collapsing them, using OVER with PARTITION BY to group and ORDER BY to order within each group. I use ROW_NUMBER, RANK and DENSE_RANK for ranking, where RANK leaves gaps after ties and DENSE_RANK does not, SUM OVER ordered for running totals, and LAG and LEAD for comparing with the previous or next row. For top N per group I number rows per partition in a subquery or CTE and filter rn less than or equal to N outside, because window functions run after WHERE."
Key words
| Word | Meaning |
|---|---|
| Window function | Calculates across related rows without collapsing them |
| OVER | Defines the window |
| PARTITION BY | Splits rows into groups for the window |
| ROW_NUMBER / RANK / DENSE_RANK | Numbering and ranking functions |
| Running total | A cumulative sum up to the current row |
| LAG / LEAD | Value from the previous / next row |
| Frame | Which neighbouring rows a window includes |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.