6.3 Time-Series SQL: LAG(), LEAD(), Running Totals & Moving Averages
Compute month-over-month revenue growth with LAG()/LEAD(), cumulative running totals with SUM() OVER(ORDER BY ...), and 7-day rolling moving averages with ROWS BETWEEN.
1. Looking Back & Ahead Across Rows: LAG() and LEAD()
Before Window Functions, comparing today's revenue with yesterday's revenue required an ugly SELF JOIN on date = date - 1.
Now LAG() peeks at the previous row and LEAD() peeks at the next row in one crisp line:
| Function | Direction | Signature | Example Use Case |
|---|---|---|---|
LAG(col, offset, default) | Looks backward | LAG(revenue, 1, 0) OVER (ORDER BY month) | Month-over-Month (MoM) growth, time since last login |
LEAD(col, offset, default) | Looks forward | LEAD(event_time) OVER (PARTITION BY user_id ORDER BY event_time) | Time until next user action, funnel drop-off |
-- Month-over-Month (MoM) Revenue Growth %
SELECT
month,
revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_month_rev,
ROUND(
100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ NULLIF(LAG(revenue) OVER (ORDER BY month), 0),
1
) AS mom_growth_pct
FROM monthly_sales
ORDER BY month;
2. Cumulative Running Totals & Sliding Window Frames (ROWS BETWEEN)
The moment you add ORDER BY inside SUM(...) OVER (ORDER BY date), SQL switches from a grand total to a cumulative running total!
Exact Frame Syntax (ROWS BETWEEN ... AND ...)
| Frame Specification | Meaning | Classic Use Case |
|---|---|---|
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW | From Row 1 up to current row | Cumulative Running Total (YTD revenue) |
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW | Current row + previous 6 rows (7 rows total) | 7-Day Moving Average (smooths noisy daily traffic!) |
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING | Previous + current + next row (3-row centered window) | Local trend smoothing |
-- Daily Revenue + Cumulative Running Total + 7-Day Moving Average
SELECT
sale_date,
revenue,
SUM(revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS cumulative_revenue,
ROUND(
AVG(revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
),
2
) AS rolling_7d_avg
FROM daily_sales
ORDER BY sale_date;
Subtle Interview Detail (
ROWSvsRANGE):
If you writeSUM(revenue) OVER (ORDER BY sale_date)without specifyingROWS, SQL defaults toRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW— which sums tiedsale_daterows together in one jump! Always writeROWS BETWEENwhen you want strict row-by-row accumulation.
3. Watch LAG() + Running Total Execute Live
| month | rev |
|---|---|
| 2026-09 | 100 |
| 2026-10 | 150 |
| 2026-11 | 200 |
4. Quick Check Your Understanding
Module 6.3 Quick Quiz
Keep Exploring: Related Lessons & Tools
All Courses →Convert Unix epoch seconds/milliseconds to ISO-8601 and local timezones, and bulk-generate UUID v4, time-ordered UUID v7, and sortable ULIDs.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.