Window
Functions
Unlock the power of row-level calculations across groups without collapsing your data: rankings, running totals, and moving averages.
What Is a Window Function?
A window function performs a calculation across a set of rows that are somehow related to the current row: this set is called the "window." Unlike a regular aggregate, the window function does not collapse rows into a single output row. Every original row keeps its identity while gaining a new computed column.
Why Window Functions Matter
Anatomy of a Window Function
The General Syntax
Aggregate vs Window
Three Categories of Window Functions
Understanding PARTITION BY
ORDER BY and the Frame Clause
ORDER BY inside the OVER clause controls the sequence of rows. Once ordered, a frame clause defines exactly which rows the function "sees" relative to the current row.
Ranking Functions Compared
| Score | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 100 | 1 | 1 | 1 |
| 95 | 2 | 2 | 2 |
| 95 | 3 | 2 | 2 |
| 80 | 4 | 4 | 3 |
LAG and LEAD
How to Apply a Window Function
Example 1: Running Total
Example 2: Ranking Sales Reps
Example 3: Month-over-Month Change
Common Mistakes to Avoid
Summary Cheat Sheet
| Function | Category | What It Does |
|---|---|---|
| ROW_NUMBER() | Ranking | Unique sequential number per partition |
| RANK() | Ranking | Rank with gaps on ties |
| DENSE_RANK() | Ranking | Rank without gaps on ties |
| SUM() OVER | Aggregate | Running total (with ORDER BY) |
| AVG() OVER | Aggregate | Moving average (with frame) |
| LAG(col, n) | Value | Value from n rows before |
| LEAD(col, n) | Value | Value from n rows after |
| NTILE(n) | Ranking | Splits rows into n equal buckets |
Question 1 of 5
What keyword distinguishes a window function from a regular aggregate function?
Question 2 of 5
Given scores 90, 85, 85, 70 ordered descending, what DENSE_RANK does the score of 70 receive?
Question 3 of 5
If you write SUM(revenue) OVER (PARTITION BY region ORDER BY month), what does each row display?
Question 4 of 5
Which function lets you access the previous row's value without a self-join?
Question 5 of 5
Why can't you use a window function directly inside a WHERE clause?