Window functions
A GROUP BY collapses rows. A window function computes across a set of rows and
keeps every row. That one difference is most of what you need.
This lesson covers four functions — ROW_NUMBER, RANK, LAG and LEAD —
and stops there on purpose. They are the ones a backend or full-stack interview
asks for. The rest of the window-function surface belongs to analytics work, and
chasing it here would trade depth on the cases you will be asked about for
breadth on the ones you will not.
The anatomy
SELECT name, department_id, salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
FROM employee
ORDER BY department_id NULLS LAST, rn;
OVERmakes it a window functionPARTITION BYsplits the rows into independent groups — likeGROUP BY, but without collapsing themORDER BYinsideOVERorders rows within the partition, which is what gives ranking and offsets their meaning
Omit PARTITION BY and the whole result is one window. Omit the inner ORDER
BY and anything position-dependent becomes non-deterministic, which is a real
bug: ROW_NUMBER() OVER () assigns numbers in whatever order the engine
produced rows, and that order can change between runs.
ROW_NUMBER versus RANK — the tie
This is the most-asked window question, and the fixture is built for it: Carol
and Dan both earn 91000.25.
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense
FROM employee
WHERE department_id = 2
ORDER BY salary DESC, name;
| name | salary | rn | rnk | dense |
|---|---|---|---|---|
| Carol | 91000.25 | 1 | 1 | 1 |
| Dan | 91000.25 | 2 | 1 | 1 |
ROW_NUMBERalways gives distinct consecutive integers. On a tie it picks one arbitrarily — and “arbitrarily” means it can differ between runs unless theORDER BYfully disambiguates.RANKgives ties the same rank and then skips: 1, 1, 3.DENSE_RANKgives ties the same rank and does not skip: 1, 1, 2.
So “top earner per department” has two different correct answers depending on
what the question wants, which is why the statement has to say. With
ROW_NUMBER, Dan disappears. With RANK, both come back.
This is the trap. A solution using ROW_NUMBER looks right, passes on data
with no ties, and silently drops rows the first time two values match. If a
problem says “return both on a tie”, ROW_NUMBER is wrong; if it says “return
exactly one per group”, ROW_NUMBER is right and RANK is wrong.
Why you cannot filter on it directly
SELECT name, salary
FROM employee
WHERE ROW_NUMBER() OVER (ORDER BY salary DESC) <= 3;
ERROR: window functions are not allowed in WHERE
From the order of operations: window functions are
computed at step 5, with SELECT, and WHERE is step 2. The window does not
exist yet. Wrap it:
SELECT name, salary
FROM (
SELECT name, salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS r
FROM employee
) ranked
WHERE r = 1
ORDER BY salary DESC, name;
Or as a CTE, which reads better for anything longer than this.
The same rule means a window function cannot appear in GROUP BY or HAVING
either — both run before SELECT.
LAG and LEAD — the previous and next row
These are how you compare a row to its neighbour without a self-join.
SELECT closed_on, amount,
LAG(amount) OVER (ORDER BY closed_on) AS previous,
amount - LAG(amount) OVER (ORDER BY closed_on) AS delta
FROM sale
WHERE employee_id = 3
ORDER BY closed_on;
The first row’s previous is NULL — there is no earlier row — so the delta
is NULL too. Supply a default if that matters:
SELECT closed_on, amount,
amount - LAG(amount, 1, 0) OVER (ORDER BY closed_on) AS delta
FROM sale
WHERE employee_id = 3
ORDER BY closed_on;
LAG(column, offset, default). LEAD is the same in the other direction.
The self-join alternative needs a join condition on consecutive ordering, which
is awkward with gaps and wrong with ties. LAG is both clearer and usually
faster, because it needs one ordered pass rather than a join.
A running total
Worth knowing because it shows the window frame, not just partition and order:
SELECT closed_on, amount,
SUM(amount) OVER (ORDER BY closed_on
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running
FROM sale
WHERE employee_id = 3
ORDER BY closed_on;
With an ORDER BY and no explicit frame, the default is RANGE BETWEEN
UNBOUNDED PRECEDING AND CURRENT ROW, which is usually what you want — except
that RANGE groups tied rows together, so on a tie every tied row shows the
same total including all of them. ROWS counts rows instead and is the one to
write when the ordering key is not unique.
Try it
The ROW_NUMBER / RANK / DENSE_RANK query side by side is the single most
useful thing to run in the SQL playground. Seeing
1,2 against 1,1 on the same two rows is what makes the distinction stick.
Drill it with
Top earner per department, whose tie
exists precisely so the two diverge, and
Month over month revenue growth for lag.
Interview questions
1. What is the difference between ROW_NUMBER, RANK and DENSE_RANK?
ROW_NUMBER always gives distinct consecutive integers, breaking ties
arbitrarily. RANK gives tied rows the same rank and skips the next values.
DENSE_RANK gives tied rows the same rank without skipping.
2. Why can a window function not appear in WHERE?
Because windows are computed with SELECT, after WHERE has already run. Wrap
the query in a subquery or CTE and filter on the computed column outside.
3. How do you return the top row per group, and what changes if there are
ties?
Rank within a partition and filter to rank 1. With ROW_NUMBER you get exactly
one row per group even on a tie; with RANK you get all tied rows. The
statement has to say which is wanted.
4. How would you compute the difference between consecutive rows?
LAG(column) OVER (ORDER BY ...) and subtract. The first row’s result is NULL
unless a default is supplied as LAG(column, 1, default).
5. What happens if you omit the ORDER BY inside OVER for ROW_NUMBER?
The numbering follows whatever order the engine produced rows in, which is not
guaranteed and can change between runs. Any position-dependent window function
needs a deterministic inner ORDER BY.
6. What is the default window frame, and when does it matter?
With an ORDER BY present it is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT
ROW. It matters on ties: RANGE includes every peer of the current row, so a
running total jumps for all tied rows at once. ROWS counts rows and avoids
that.
Next
That closes Part 2. How an index works opens Part 3, where the question shifts from what a query returns to what it costs.