Window Functions in SQL — RANK, LEAD, LAG with Real Examples
Contents
If you've ever needed to rank products within a category, compare revenue to the previous month, or calculate a cumulative total — and ended up with nested subqueries or temp tables — window functions are exactly what you need.
What are window functions and why do they matter?
Window functions compute a value for each row, considering a set of related rows ("the window") — but without grouping the data. The result appears in a new column while all original rows are preserved.
Compared to GROUP BY:
-- GROUP BY: 3 input rows → 1 output row (you lose detail)
SELECT category, SUM(revenue) AS total
FROM orders
GROUP BY category;
-- Window function: 3 input rows → 3 output rows (detail preserved)
SELECT
order_id,
category,
revenue,
SUM(revenue) OVER (PARTITION BY category) AS category_total
FROM orders;The OVER clause — how it works
OVER() is the heart of every window function. It defines the "window" — which rows are considered when computing the value for a given row.
Syntax:
FUNCTION() OVER (
PARTITION BY column -- optional: divide into groups
ORDER BY column -- optional: sort rows within the window
ROWS BETWEEN ... -- optional: limit window size
)RANK, DENSE_RANK, ROW_NUMBER — when to use which?
All three assign numbers to rows. The difference shows up on ties:
RANK: tie → both get 1, next gets 3 (skips 2)DENSE_RANK: tie → both get 1, next gets 2 (no gap)ROW_NUMBER: always unique — if there's a tie, the order between tied rows depends onORDER BYdeterminism
For deduplication, use ROW_NUMBER — it guarantees exactly one "winner" per group.
PARTITION BY — group without grouping
PARTITION BY resets the calculation for each group — as if you ran the function separately for each category, country, or customer.
Without PARTITION BY — the function works on the entire table. With PARTITION BY customer_id — numbering and sums reset for each customer.
LAG and LEAD — period-over-period comparisons
LAG(col, n) returns the value from n rows back. LEAD(col, n) returns the value from n rows ahead. Perfect for MoM or YoY growth calculations.
SELECT
month,
revenue,
LAG(revenue, 1, 0) OVER (ORDER BY month) AS prev_month_revenue,
ROUND(
100.0 * (revenue - LAG(revenue, 1) OVER (ORDER BY month))
/ NULLIF(LAG(revenue, 1) OVER (ORDER BY month), 0),
1
) AS mom_growth_pct
FROM monthly_revenue
ORDER BY month;The third argument LAG(col, 1, 0) is the default value when there's no previous row (first month). Without it you get NULL and the growth calculation breaks. NULLIF(x, 0) protects against division by zero.
Cumulative sums and rolling averages
ROWS BETWEEN defines the window frame — which specific rows go into the calculation:
SELECT
date,
daily_revenue,
SUM(daily_revenue) OVER (
ORDER BY date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS cumulative_revenue,
AVG(daily_revenue) OVER (
ORDER BY date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS rolling_7d_avg
FROM daily_sales;Snowflake tip: the official documentation recommends always declaring the frame explicitly (ROWS BETWEEN ...). Without it, behavior follows defaults that can be non-obvious — explicit declaration eliminates confusion.
QUALIFY in Snowflake
In standard SQL, filtering by a window function requires a CTE or subquery. Snowflake has QUALIFY — a filter that works directly on window function results:
-- Standard SQL
WITH ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn
FROM users
)
SELECT * FROM ranked WHERE rn = 1;
-- Snowflake QUALIFY — same result, more readable
SELECT *
FROM users
QUALIFY ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) = 1;Common mistakes
Mistake 1: Filtering by window function in WHERE. WHERE executes before window functions — you can't filter on their result there. Use a CTE + WHERE or Snowflake's QUALIFY.
Mistake 2: Missing ORDER BY with LAG/LEAD. Without ORDER BY in OVER(), row order is undefined — LAG may return a random row.
Mistake 3: Confusing PARTITION BY with GROUP BY. PARTITION BY doesn't reduce rows — it only segments the window. GROUP BY reduces rows.
TL;DR
- Window functions = aggregate + preserve all rows — use when you need both
OVER(PARTITION BY x ORDER BY y)is the key to understanding how windows workROW_NUMBERfor deduplication,RANK/DENSE_RANKfor rankings (tie behavior matters)LAG(col, 1, 0)for MoM/YoY — third argument as fallback for the first row- Declare
ROWS BETWEENexplicitly — Snowflake documentation recommendation - In Snowflake:
QUALIFYeliminates the need for a CTE when filtering on window functions
Is your data scattered across several places?
I help build a warehouse and pipelines that refresh on their own. The first call is free.
Book a consultationMore articles about data analytics:
Back to blog