Skip to main content

Chapter 8 · Window Functions

SQL Window Functions Practice

Window functions compute a value for each row using other rows around it, without collapsing them like GROUP BY does. They answer the questions that are hard any other way: top N per group, running totals, month-over-month change.

They're the most tested advanced SQL topic in data analyst and data engineer interviews, and the one that separates beginners from confident SQL users.

Start practising62 exercises · 0 easy, 14 medium, 48 hard

Key ideas

OVER (PARTITION BY … ORDER BY …)
Defines the window: which rows belong together and in what order.
ROW_NUMBER, RANK, DENSE_RANK
Number rows within each group. They differ only in how ties are handled.
LAG / LEAD
Read the previous or next row's value: perfect for period-over-period change.
Running totals
SUM(x) OVER (ORDER BY date) adds up values row by row.

Example: Top 3 most expensive products in each category

SELECT *
FROM (
  SELECT name, category_id, price,
         RANK() OVER (PARTITION BY category_id
                      ORDER BY price DESC) AS price_rank
  FROM products
) ranked
WHERE price_rank <= 3;

RANK restarts at 1 for every category; the outer query keeps the first three of each.

In interviews

"Top N per group" is the single most common advanced SQL interview question. Know it with ROW_NUMBER and with RANK, and explain which one you'd pick when there are ties.

All 62 Window Functions exercises

Ordered from easiest to hardest. Each one runs on a real database with instant feedback.