Window Functions
Ranking, running totals, moving averages and period-over-period comparisons without collapsing rows.
Intermediate · about 6 hours · difficulty 4/5
Learn first: Subqueries and CTEs
Window functions compute across a set of related rows while keeping every row. They unlock questions that are painful with GROUP BY alone.
Syntax
SELECT order_id, customer_id, order_date, amount,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) AS order_seq,
SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_spend
FROM orders;
- PARTITION BY defines groups (like GROUP BY without collapsing).
- ORDER BY inside OVER defines the sequence.
- A frame (
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) defines a sliding window.
The toolkit
- Ranking:
ROW_NUMBER,RANK,DENSE_RANK,NTILE. Top N per group and deduplication ("keep the latest row per id"). - Offsets:
LAG,LEADfor month-over-month change and time between events. - Aggregates over windows: running totals, moving averages, percent of total (
amount / SUM(amount) OVER ()). - FIRST_VALUE / LAST_VALUE: careful, LAST_VALUE needs an explicit frame to behave as expected.
Filtering on window results
You cannot use a window function in WHERE; wrap it in a CTE and filter outside. Some warehouses support QUALIFY for this.
Pitfall: confusing RANK and ROW_NUMBER when ties exist, and the default frame with ORDER BY being "range up to current row", which groups ties together. Move on when you can write a month-over-month growth query and a top-3-per-category query from memory.
Key concepts
- OVER, PARTITION BY, ORDER BY
- ROW_NUMBER, RANK, DENSE_RANK
- LAG and LEAD
- Running totals and moving averages
- Window frames
- Percent of total
- Deduplication with ROW_NUMBER
- QUALIFY clause: Snowflake, BigQuery, DuckDB
Mini project
With a public daily sales or Citi Bike trips table, compute daily totals, a 7-day moving average, week-over-week change and each station's rank within its borough.
Check yourself
How would you keep only the most recent record per customer from a table with many updates per customer?
Free resources
- PostgreSQL: window functions tutorial (PostgreSQL)
- Mode SQL Tutorial (Mode)
- Advanced SQL (Kaggle)