01 / 22

Window
Functions

Unlock the power of row-level calculations across groups without collapsing your data: rankings, running totals, and moving averages.

Business Analytics

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

Rankings
Rank sales reps, students, or products without sub-queries or self-joins.
Running Totals
Compute cumulative revenue month by month while keeping every monthly row visible.
Comparisons
Compare each row to the previous row, group average, or a moving average: all in one query.

Anatomy of a Window Function

SUM(revenue) OVER (PARTITION BY region ORDER BY month) Function OVER PARTITION BY ORDER BY What to compute Signals a window Defines groups Row order inside

The General Syntax

SELECT column_list, window_function(expression) OVER ( PARTITION BY partition_column ORDER BY order_column -- optional frame clause ) AS alias FROM table_name;

Aggregate vs Window

GROUP BY (Aggregate) East 100 East 200 West 150 West 250 East 300 West 400 2 rows out (collapsed) OVER (Window) East 100 East 200 West 150 West 250 East 100 300 East 200 300 West 150 400 West 250 400 4 rows out (kept all)

Three Categories of Window Functions

Aggregate
SUM, AVG, COUNT, MIN, MAX: the same functions you know, but used with OVER.
Ranking
ROW_NUMBER, RANK, DENSE_RANK, NTILE: assign positions within each partition.
Value / Offset
LAG, LEAD, FIRST_VALUE, LAST_VALUE: access data from other rows without a self-join.

Understanding PARTITION BY

Partition: East Jan East 100 Feb East 200 Mar East 150 SUM = 450 Partition: West Jan West 250 Feb West 300 Mar West 350 SUM = 900 Each partition is an independent "mini-table" for the window function

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.

ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW -- This is the default when ORDER BY is present. -- It gives a "running total" from start to current row.

Ranking Functions Compared

Score ROW_NUMBER RANK DENSE_RANK
100111
95222
95322
80443

LAG and LEAD

Jan 100 LAG: NULL Feb 200 LAG: 100 Mar ★ 150 LAG: 200 LEAD: 300 Apr 300 LAG LEAD For the current row (Mar): LAG looks back one row, LEAD looks forward one row

How to Apply a Window Function

1
Decide your goal: ranking, running total, row comparison, or moving average?
2
Choose the function: ROW_NUMBER, SUM, AVG, LAG, LEAD, etc.
3
Define the partition: which column(s) should create separate groups? (PARTITION BY)
4
Set the order: how should rows be sequenced inside each partition? (ORDER BY)
5
Optionally set a frame: ROWS BETWEEN ... limits which rows the function considers.

Example 1: Running Total

SELECT month, region, revenue, SUM(revenue) OVER ( PARTITION BY region ORDER BY month ) AS running_total FROM sales;
month region revenue running_total Jan East 100 100 Feb East 200 300 Mar East 150 450 Jan West 250 250 Feb West 300 550

Example 2: Ranking Sales Reps

SELECT rep_name, total_sales, RANK() OVER ( ORDER BY total_sales DESC ) AS sales_rank FROM reps;
rep_name total_sales sales_rank Alice 5000 1 Bob 4200 2 Carol 4200 2 Dave 3800 4

Example 3: Month-over-Month Change

SELECT month, revenue, LAG(revenue, 1) OVER (ORDER BY month) AS prev_rev, revenue - LAG(revenue, 1) OVER (ORDER BY month) AS change FROM monthly_sales;
month revenue prev_rev change Jan 1000 NULL NULL Feb 1200 1000 +200 Mar 900 1200 -300 Apr 1100 900 +200

Common Mistakes to Avoid

✕ Using in WHERE
Window functions cannot appear in a WHERE clause. Use a sub-query or CTE, then filter the outer query.
✕ Forgetting ORDER BY
Without ORDER BY in OVER, SUM gives the partition total on every row: no running total at all.
✕ Mixing with GROUP BY
Combining GROUP BY with window functions on the same query level can produce unexpected results. Aggregate first in a CTE.

Summary Cheat Sheet

Function Category What It Does
ROW_NUMBER()RankingUnique sequential number per partition
RANK()RankingRank with gaps on ties
DENSE_RANK()RankingRank without gaps on ties
SUM() OVERAggregateRunning total (with ORDER BY)
AVG() OVERAggregateMoving average (with frame)
LAG(col, n)ValueValue from n rows before
LEAD(col, n)ValueValue from n rows after
NTILE(n)RankingSplits 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?