LEAD, LAG & Running Totals
Look at the next or previous row's value and build running sums — the two most powerful patterns in analytical SQL.
LEAD peeks at the next row. LAG looks at the previous one. SUM OVER builds a running total. These three unlock trend analysis.
EXERCISE
1LAG & LEAD — Looking at Neighbouring Rows
LAG accesses the previous row's value. LEAD accesses the next row's value. Together they unlock trend analysis, change detection, and month-over-month comparisons.
LAG — look backward:
LAG(column, offset, default) OVER (ORDER BY ...)
-- offset: how many rows back (default 1)
-- default: what to return if no previous row exists (default NULL)
-- Monthly sales with previous month comparison:
SELECT
month,
revenue,
LAG(revenue, 1, 0) OVER (ORDER BY month) AS prev_month_revenue,
revenue - LAG(revenue, 1, 0) OVER (ORDER BY month) AS month_over_month_change
FROM monthly_sales
ORDER BY month;
Output:
+-------+---------+--------------------+------------------------+
| month | revenue | prev_month_revenue | month_over_month_change|
+-------+---------+--------------------+------------------------+
| 1 | 50000 | 0 | 50000 |
| 2 | 62000 | 50000 | 12000 |
| 3 | 58000 | 62000 | -4000 |
| 4 | 71000 | 58000 | 13000 |
+-------+---------+--------------------+------------------------+
LEAD — look forward:
-- Show each order alongside the next order date for the same customer:
SELECT
customer_id,
order_date,
LEAD(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS next_order_date,
DATEDIFF(
LEAD(order_date) OVER (PARTITION BY customer_id ORDER BY order_date),
order_date
) AS days_until_next_order
FROM orders;
Detecting price changes:
-- Find products whose price changed from the previous snapshot:
SELECT product_id, snapshot_date, price,
LAG(price) OVER (PARTITION BY product_id ORDER BY snapshot_date) AS prev_price
FROM price_history
HAVING prev_price IS NOT NULL AND price != prev_price;
Pro Tip: LAG and LEAD are the window functions for time-series analysis. Any time you need "this value vs the previous period" or "days between events", reach for them.
EXERCISE
2Running Totals and Moving Averages with SUM OVER
SUM() OVER with ORDER BY creates a running total — one of the most requested analytics features and a staple of every financial and operational report.
Running total — cumulative SUM:
SELECT
order_date,
daily_revenue,
SUM(daily_revenue) OVER (ORDER BY order_date) AS running_total
FROM daily_sales
ORDER BY order_date;
Output:
+------------+---------------+---------------+
| order_date | daily_revenue | running_total |
+------------+---------------+---------------+
| 2024-01-01 | 12000 | 12000 |
| 2024-01-02 | 8500 | 20500 |
| 2024-01-03 | 15000 | 35500 |
| 2024-01-04 | 9200 | 44700 |
+------------+---------------+---------------+
Running total per partition (per customer, per product, etc.):
SELECT
customer_id,
order_date,
amount,
SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY order_date
) AS customer_running_total
FROM orders;
-- Each customer's running total resets independently
Moving average — smooth out noise:
-- 3-day moving average of revenue:
SELECT
order_date,
daily_revenue,
AVG(daily_revenue) OVER (
ORDER BY order_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS moving_avg_3day
FROM daily_sales;
-- Window: current row + 2 rows before it = 3-day window
ROWS vs RANGE in window frames:
-- ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW → standard running total
-- ROWS BETWEEN 2 PRECEDING AND CURRENT ROW → rolling 3-row window
-- ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING → centered moving average
Pro Tip:
SUM(col) OVER (ORDER BY date)is the SQL running total. No self-join, no subquery, no CTE needed. It is one of the most elegantly solved problems in modern SQL.
EXERCISE
3Window Functions — The PARTITION BY Deep Dive
PARTITION BY is the heart of window functions — it defines which rows form the "window" for each calculation, letting you do per-group analysis without losing individual rows.
Without PARTITION BY — the window is the entire result set:
SELECT name, salary,
AVG(salary) OVER () AS company_avg
FROM employees;
-- Every row shows the same company-wide average
With PARTITION BY — the window is each group:
SELECT name, department, salary,
AVG(salary) OVER (PARTITION BY department) AS dept_avg,
salary - AVG(salary) OVER (PARTITION BY department) AS diff_from_dept_avg
FROM employees;
-- Each row shows its own department's average
-- Rows in IT see the IT average; rows in HR see the HR average
Combining PARTITION BY and ORDER BY:
-- Running total per department (resets for each department):
SELECT department, name, salary,
SUM(salary) OVER (
PARTITION BY department
ORDER BY salary DESC
) AS dept_running_total
FROM employees
ORDER BY department, salary DESC;
Practical pattern — percentage of department total:
SELECT
name,
department,
salary,
SUM(salary) OVER (PARTITION BY department) AS dept_total,
ROUND(salary * 100.0 / SUM(salary) OVER (PARTITION BY department), 1) AS pct_of_dept
FROM employees
ORDER BY department, salary DESC;
Key rules:
PARTITION BYwithoutORDER BY→ aggregate over entire partition (like GROUP BY but keeps rows)PARTITION BYwithORDER BY→ cumulative calculation within partition- Neither → aggregate over all rows
Pro Tip: PARTITION BY is to window functions what GROUP BY is to aggregates — except GROUP BY collapses rows while PARTITION BY keeps them. This is the core difference to memorise.
