Window Functions
7 pages · ~5 min✓ Reviewed
Builds on Subqueries and CTEs. Next up: Indexes and Query Plans.
Window Functions Mental Model
1. What a Window Function Is
- Computes a value per row over a set of related rows
- Rows are not collapsed; GROUP BY returns one row per group
OVER()turns an aggregate or ranking function into a window function- Empty
OVER()= window is the whole result set
2. PARTITION BY and ORDER BY
| Inside OVER | Effect |
|---|---|
PARTITION BY | Independent groups; function restarts in each |
ORDER BY | Row order in the partition |
ORDER BY + aggregate | Default frame becomes running |
SELECT cust, d, amount, SUM(amount) OVER ( PARTITION BY cust ORDER BY d ) AS running FROM orders;
running total restarts per customer
3. Where It Runs
- WHERE
- GROUP BY
- HAVING
- Window
- ORDER BY, LIMIT
Ranking: ROW_NUMBER, RANK, DENSE_RANK
1. Three Ranking Functions
| Function | Scores 90, 80, 80, 70 | Ties |
|---|---|---|
ROW_NUMBER() | 1, 2, 3, 4 | unique, never tied |
RANK() | 1, 2, 2, 4 | same number, gap after |
DENSE_RANK() | 1, 2, 2, 3 | same number, no gap |
LAG and LEAD
1. Looking at Other Rows
LAG(col, n, default)reads n rows before the current rowLEAD(col, n, default)reads n rows after- Defaults: n = 1, default = NULL
- First row of a partition: LAG gives NULL unless a default is set
2. Month-over-Month Change
SELECT month, amount, amount - LAG(amount) OVER (ORDER BY month) AS change FROM sales;
| month | amount | change |
|---|---|---|
| Jan | 100 | NULL |
| Feb | 120 | 20 |
| Mar | 90 | -30 |
current row minus previous row
Running Totals and Frames
1. Frame Clause
ROWS | RANGE | GROUPS BETWEEN start AND end- Bounds: UNBOUNDED PRECEDING,
n PRECEDING, CURRENT ROW,n FOLLOWING, UNBOUNDED FOLLOWING
- With ORDER BY: default is
RANGE UNBOUNDED PRECEDINGtoCURRENT ROW - No ORDER BY: default is the whole partition
2. ROWS vs RANGE
Top-N per Group and Common Mistakes
1. The Top-N Pattern
- Rank in a CTE or subquery, then filter
WHERE rn <= Nin the outer query - Window functions can't be filtered in the same SELECT's WHERE, so wrap them first
WITH r AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY g ORDER BY v DESC) rn FROM t) SELECT * FROM r WHERE rn <= 3;
top 3 per group
2. Ties and Latest Row
Window Functions Cheat Sheet
1. Syntax and Ranking
func() OVER (PARTITION BY cols ORDER BY cols frame)- Ranking needs ORDER BY inside OVER
| Function | On ties | Output |
|---|---|---|
ROW_NUMBER | unique | 1,2,3,4 |
RANK |
Check yourself
Salaries 90, 80, 80, 70 sorted DESC. What do ROW_NUMBER, RANK and DENSE_RANK return?
ROW_NUMBER: 1, 2, 3, 4 (tie order arbitrary)RANK: 1, 2, 2, 4 (gap after the tie)DENSE_RANK: 1, 2, 2, 3 (no gap)
Why does WHERE rn <= 3 fail when rn is a ROW_NUMBER in the same SELECT?
WHEREruns before window functions, sorndoes not exist yet- Compute
rnin a CTE, then filter in the outer query