I’ll be honest: window functions changed how I write SQL. Before I really understood them, I was writing huge subqueries and self-joins just to calculate running totals. Then I learned OVER() and my queries got a lot shorter.
The idea: a window function does a calculation across a set of rows but keeps every original row. A normal aggregate like SUM() with GROUP BY collapses each group into one row; a window function gives you the result on every row instead.
The OVER() Clause
OVER() is what turns a function into a window function. You can leave it empty (the window is the whole result set) or add PARTITION BY and ORDER BY.
PARTITION BY splits rows into groups, like GROUP BY but without collapsing them. Each group gets its own calculation.
ORDER BY sorts rows within each group. You need it for rankings and running totals, otherwise the order (and the result) is arbitrary.
The basic pattern:
WINDOW_FUNCTION() OVER (
PARTITION BY column1, column2
ORDER BY column3
)
Ranking Functions
These are the ones I reach for most:
ROW_NUMBER() gives each row a unique number. Handy for grabbing the Nth record in each group.
RANK() gives ties the same number, then skips. Two people tie for 2nd, the next person is 4th.
DENSE_RANK() gives ties the same number without skipping. Two tie for 2nd, the next is 3rd.
NTILE(n) splits rows into n roughly equal buckets. Good for quartiles or deciles.
A classic use: find the top-selling product in each region.
WITH ranked AS (
SELECT
product,
region,
amount,
ROW_NUMBER() OVER(PARTITION BY region ORDER BY amount DESC) as regional_rank
FROM sales
)
SELECT product, region, amount
FROM ranked
WHERE regional_rank = 1; -- Only the #1 product per region
You can’t filter on a window function in the same query’s WHERE (WHERE runs before the window is calculated), so it goes in a CTE first. Without window functions, this would be a self-join with a correlated subquery. On Snowflake, BigQuery or DuckDB you can skip the CTE and use QUALIFY regional_rank = 1 instead.
If ties matter (two products with the same top amount), use RANK() so both come back; ROW_NUMBER() picks one arbitrarily.
LAG() and LEAD()
LAG() looks at a previous row, LEAD() at a following one. Very useful for time series.
LAG(sales_amount, 1, 0) -- Previous row's sales, default to 0 if none
LEAD(sales_amount, 1, 0) -- Next row's sales, default to 0 if none
Day-over-day sales change:
SELECT
sale_date,
amount,
LAG(amount, 1) OVER(ORDER BY sale_date) as prev_day,
amount - LAG(amount, 1) OVER(ORDER BY sale_date) as daily_change
FROM sales
The first row has NULL for prev_day because there’s no earlier row. Wrap it in COALESCE() if you need a value there.
Running Totals
Any regular aggregate becomes a window function when you add OVER(). That’s how you get a running total without subqueries or self-joins:
SELECT
sale_date,
amount,
SUM(amount) OVER(ORDER BY sale_date) as running_total
FROM sales
That’s the whole thing. Each row shows the cumulative sum up to that date.
Window Frames
Sometimes you don’t want the whole partition, just the last few rows, or a few on either side. ROWS BETWEEN sets exactly which rows go into the calculation.
A 3-day rolling average to smooth out noisy sales data:
SELECT
sale_date,
amount,
AVG(amount) OVER(
ORDER BY sale_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) as three_day_avg
FROM sales
This covers today plus the previous 2 rows. You can also use FOLLOWING, or mix them, e.g. BETWEEN 1 PRECEDING AND 1 FOLLOWING for a centered window. Note that ROWS counts rows, not days: if a date is missing, the “3-day” window quietly stretches further back.
Where to Start
Start with ROW_NUMBER() and LAG(). Between them they replace most of the subqueries people write for “latest record per group” and “change since last time.”
Want to practice? DataLemur has good datasets. Or take a messy query you wrote recently and rewrite it with window functions. It’s usually a lot shorter afterwards.