SQL for Data Analysis: Window Functions Explained
When performing advanced data analysis, aggregations, or financial reporting in relational databases, standard GROUP BY clauses often fall short. Grouping compresses rows together, making it impossible to evaluate individual transaction records alongside aggregated metrics simultaneously. To calculate running totals, moving averages, year-over-year growth, or row rankings without collapsing your dataset, database engineers rely on SQL Window Functions.
This comprehensive guide explores the internal mechanics of window functions, syntax structures, and practical SQL queries covering ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, and running aggregations.
1. What is a Window Function and How Does It Work?
Unlike aggregate functions that collapse multiple rows into a single summary row, a window function performs a calculation across a set of table rows that are somehow related to the current row. This set of rows is defined by the OVER() clause.
- PARTITION BY: Divides the rows into smaller partitions or groups (analogous to
GROUP BY, but without collapsing rows). - ORDER BY: Defines the logical sorting order of rows within each partition.
- Rows/Range Frame: Restricts the window frame further (e.g., preceding or following row boundaries).
2. Ranking Functions: ROW_NUMBER, RANK, and DENSE_RANK
Ranking functions assign sequential integers to rows within a partition. Understanding their differences when handling ties is essential for analytics.
-- SQL Query demonstrating ranking functions across department salaries
SELECT
employee_name,
department,
salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) as row_num,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) as rank_num,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) as dense_rank_num
FROM employees;
3. Value Functions: LAG and LEAD for Time-Series Analysis
LAG() and LEAD() allow you to access data from a previous or subsequent row within the same result set without needing self-joins. This is invaluable for calculating period-over-period growth or session durations.
-- Calculating monthly revenue growth using LAG()
SELECT
month,
revenue,
LAG(revenue, 1) OVER (ORDER BY month) as previous_month_revenue,
revenue - LAG(revenue, 1) OVER (ORDER BY month) as revenue_growth
FROM monthly_sales;
4. Aggregate Window Functions: Running Totals and Moving Averages
You can turn standard aggregate functions (SUM, AVG, COUNT) into window functions by appending the OVER() clause, enabling seamless calculations of running totals and moving averages.
-- Calculating running cumulative totals of sales per customer
SELECT
customer_id,
order_date,
order_amount,
SUM(order_amount) OVER (
PARTITION BY customer_id
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) as running_total
FROM orders;
Conclusion
Mastering SQL window functions—from ranking partitions with ROW_NUMBER and comparing historical data points with LAG to computing running totals—transforms how you analyze relational data, enabling clean, highly efficient analytical queries.