Window Functions

Calculate across related rows, like a running total or a rank, without collapsing them as GROUP BY does.

What is it?

Aggregation collapses rows into one summary per group: one row per customer, one per category. Sometimes you want to keep every row but add a value computed from its group: "each order plus the customer's running total so far," or "each product's price plus its rank in its category."

A window function does this with OVER (...), optionally using PARTITION BY (which rows form a group) and ORDER BY (their order within the group). Unlike GROUP BY, it doesn't merge rows. Every row stays, with an extra computed column.

Explain like I'm 10

GROUP BY hands a customer one combined receipt total. A window function hands back every line item, each with a running total (or a rank against everything else they bought) printed on it. Nothing is merged away; each line just gains context.

Examples

Ranking within a partition

SELECT name, category, price,
  RANK() OVER (PARTITION BY category ORDER BY price DESC) AS price_rank
FROM products;

Every product row is kept, and each also shows its price rank within its category, highest first.

A running total

SELECT id, amount,
  SUM(amount) OVER (ORDER BY id) AS running_total
FROM payments;

Each row shows its amount plus the cumulative sum of every row up to and including it, in id order. No GROUP BY, no rows merged.

How it works

For each output row, the database finds its "window": the rows that belong with it (from PARTITION BY), in the order from ORDER BY. It computes the function (RANK, SUM, ROW_NUMBER, LAG/LEAD, and others) over that window.

The original row is still returned as-is, with the result as an extra column. That's the core difference from GROUP BY, which discards the individual rows and returns one row per group.

Why does it exist?

Before window functions, "rank within category" or "running total" needed a self-join or a correlated subquery per row. That's verbose and slow at scale, because related rows are reprocessed for every output row instead of computed in one pass.

When to use it

Use window functions for leaderboards and rankings, running totals or moving averages, comparing a row with the previous or next one (LAG/LEAD), and "top N rows per group" queries.

When not to use it

If you want one summary row per group and don't need the individual rows, plain GROUP BY is simpler and says exactly that.

Common mistakes

  • Leaving out PARTITION BY, so the rank or total runs across the whole table instead of restarting per group.

  • Mixing up RANK (gaps after ties), DENSE_RANK (no gaps after ties), and ROW_NUMBER (always unique and sequential, ties broken arbitrarily).

  • Filtering on a window function's result in WHERE. That's not allowed, because WHERE runs before window functions are computed.

Practice exercises

  1. Easy:

    Use ROW_NUMBER() to number each customer's orders in the order they were placed.

  2. Medium:

    Show each employee's salary with their salary rank within their department.

  3. Hard:

    Explain why WHERE price_rank = 1 fails right after a window function that computes price_rank, and rewrite the query with a CTE so it works.

Interview questions

What's the fundamental difference between GROUP BY and a window function?

GROUP BY collapses rows into one summary row per group. A window function keeps every row and still computes a value using the row's group as context.

What's the difference between RANK, DENSE_RANK, and ROW_NUMBER?

RANK leaves gaps after a tie (1, 1, 3), DENSE_RANK doesn't (1, 1, 2), and ROW_NUMBER always gives a unique sequential number, ties or not.

Why can't you filter directly on a window function's result in a WHERE clause?

WHERE runs before window functions, so the value doesn't exist yet. Compute it in a subquery or CTE and filter in the outer query.

What does PARTITION BY control, and what happens if you omit it entirely?

It sets which rows form one group for the calculation. Without it, the whole result is one partition, so the function runs across every row instead of restarting per group.

What does ORDER BY inside an OVER(...) clause do for a running-total-style SUM, that's different from its role in RANK?

For RANK it sets the ranking order. For an aggregate like SUM it sets the order rows accumulate in, which, with the default frame, turns a plain sum into a running total up to the current row.

Given `payments(id, amount)` = (1,100), (2,50), (3,200), what does `SELECT id, amount, SUM(amount) OVER (ORDER BY id) AS running_total FROM payments;` output, row by row?

id 1: 100, id 2: 150, id 3: 350. With ORDER BY and no explicit frame, each total adds up every row from the start of the partition through the current row, in id order.

What is a window function's 'frame', and how does it differ from its partition?

The partition is the whole group a row belongs to. The frame is the subset of rows within it (e.g. 'from the start to the current row') that the function computes over for that row. One partition has many frames as you move from row to row.

What's the default frame for an aggregate window function when ORDER BY is given but no explicit ROWS/RANGE clause is specified?

RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: everything from the start of the partition through the current row (and, with RANGE, any rows tied with it on the ORDER BY value).

Given `products(name, category, price)` = (Alpha, Electronics, 300), (Beta, Electronics, 300), (Gamma, Electronics, 100), (Delta, Furniture, 500), what does `RANK() OVER (PARTITION BY category ORDER BY price DESC)` give each row, versus DENSE_RANK and ROW_NUMBER?

Electronics: Alpha and Beta tie for top price. RANK gives both 1 and Gamma 3 (skipping 2). DENSE_RANK gives them 1 and Gamma 2 (no gap). ROW_NUMBER gives Alpha/Beta 1 and 2 in arbitrary tie-broken order, and Gamma 3. Furniture is its own partition, so Delta gets 1 in all three.

Why do RANK and DENSE_RANK produce identical results when there are no ties in the ORDER BY column, but diverge as soon as a tie appears?

Without ties, each row just gets the next number either way. Only a tie makes RANK skip ahead (to account for the tied rows), while DENSE_RANK keeps counting without a gap.

What does LAG() return for the very first row in its partition, by default, and why?

NULL. The first row has no previous row, and LAG returns NULL in that case unless you give a default.

Given `stock_prices(day, price)` = (1,10), (2,12), (3,9), what does `LAG(price) OVER (ORDER BY day)` output for each row?

day 1: NULL, day 2: 10, day 3: 12. Each row shows the previous day's price; the first has none.

How would you make LAG() return 0 instead of NULL for the first row?

Pass a default as the third argument: LAG(price, 1, 0) means one row back, defaulting to 0 when there's no such row.

What's the difference between LAG/LEAD and FIRST_VALUE/LAST_VALUE?

LAG/LEAD look a fixed number of rows before or after the current row. FIRST_VALUE/LAST_VALUE return the value from the first or last row of the current frame, however far away.

Why does LAST_VALUE often unexpectedly return the current row's own value instead of the actual last row in the partition?

With the default frame (up to the current row), the last row of the frame is the current row. To get the true last row of the partition, widen the frame, e.g. ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.

What is `ROWS BETWEEN n PRECEDING AND CURRENT ROW` used for, and how does it differ from the default frame?

It computes over a fixed sliding window of the previous n rows plus the current one (handy for moving averages), instead of the default ever-growing window from the start of the partition.

Given `sales(day, amount)` = (1,10), (2,20), (3,30), what does `SUM(amount) OVER (ORDER BY day ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)` output?

day 1: 10 (no previous row, so just itself), day 2: 30 (10+20), day 3: 50 (20+30). A 2-row moving sum, not a running total.

What's the difference between a ROWS frame and a RANGE frame when there are duplicate ORDER BY values?

ROWS counts physical rows, ignoring ties. RANGE includes every row sharing the boundary row's ORDER BY value, so tied rows can be pulled into the frame together, even beyond the row count you'd expect.

How would you get the top 2 highest-priced products per category using a window function?

Compute ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn in a CTE or subquery, then filter the outer query with WHERE rn <= 2.

Why do you need a subquery or CTE to actually filter to 'top N per group', rather than adding a WHERE or LIMIT directly?

WHERE runs before the window function exists, and LIMIT caps the whole result rather than each group. Both need the rank to already be a column, which only a wrapping subquery or CTE gives you.

How could you use ROW_NUMBER() to remove exact duplicate rows from a table, keeping just one copy of each?

Partition by the columns that define a duplicate, number rows in each partition with ROW_NUMBER(), and delete (or exclude in a query) every row numbered above 1.

Can you use one window function's result as an argument to another window function in the same SELECT list without a subquery?

No. Window functions are computed at the same late stage, so one can't see another's output. Compute the first in a subquery or CTE, then use that column in an outer window function.

Where do window functions fit in SQL's logical order of query processing, relative to WHERE, GROUP BY/HAVING, and the final SELECT list?

After WHERE, GROUP BY, and HAVING (so they see filtered, grouped rows), but before the SELECT list's ordinary expressions and before ORDER BY/DISTINCT. That's why WHERE can't use their results, but ORDER BY can.

Why can an aggregate window function like SUM() OVER(...) appear in the same query as a plain GROUP BY aggregate, and what would that combination be useful for?

They run at different stages, so they can coexist. For example, group to get per-department totals while a window function compares each row against a separate window, like each employee's salary against the department average, in one query.

What's the performance concern with computing a window function's PARTITION BY/ORDER BY over a very large, unindexed column?

The database usually needs rows sorted by the partition and order columns. Without a supporting index, it may sort the whole result from scratch, which gets expensive as rows grow.

How does a window function's performance generally compare to an equivalent correlated subquery computing the same per-row value, and why?

A window function usually runs in one pass over partitioned, sorted data. A correlated subquery reruns its inner query for every outer row, usually doing far more repeated work.

What does NTILE(4) OVER (ORDER BY score) compute, conceptually?

It splits the ordered rows into 4 roughly equal buckets and labels each row with its bucket (1 to 4). Useful for quartiles and similar equal-sized groups.

Debugging: a query with `RANK() OVER (PARTITION BY department ORDER BY salary DESC)` returns rank 1 for every single row. What's the most likely mistake?

The ORDER BY inside OVER(...) is missing or not applied. With no ordering, every row in a partition ties with every other, so RANK() gives them all 1.

Why is it a mistake to assume window functions always run slower than writing the same logic as a self-join?

A window function usually runs in one pass over data partitioned and sorted once. A self-join rescans and rematches the table against itself, which is usually much more expensive.

What can a window function do that a plain aggregate function used without OVER() fundamentally cannot?

Keep every row in the output while computing a value from its group, instead of collapsing the group into one row.