SQL · Module 06: Window Functions (SQL Interview Superpower)Tutorial 18 of 24
All Tutorials·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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:

FunctionDirectionSignatureExample Use Case
LAG(col, offset, default)Looks backwardLAG(revenue, 1, 0) OVER (ORDER BY month)Month-over-Month (MoM) growth, time since last login
LEAD(col, offset, default)Looks forwardLEAD(event_time) OVER (PARTITION BY user_id ORDER BY event_time)Time until next user action, funnel drop-off
SQL
-- 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 SpecificationMeaningClassic Use Case
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWFrom Row 1 up to current rowCumulative Running Total (YTD revenue)
ROWS BETWEEN 6 PRECEDING AND CURRENT ROWCurrent row + previous 6 rows (7 rows total)7-Day Moving Average (smooths noisy daily traffic!)
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWINGPrevious + current + next row (3-row centered window)Local trend smoothing
SQL
-- 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 (ROWS vs RANGE):
If you write SUM(revenue) OVER (ORDER BY sale_date) without specifying ROWS, SQL defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW — which sums tied sale_date rows together in one jump! Always write ROWS BETWEEN when you want strict row-by-row accumulation.


3. Watch LAG() + Running Total Execute Live

Tracing LAG() & Cumulative Running Total
Interactive SQL Execution Tracer · Step 1 of 3 (1. Load monthly_sales (ordered by month))
1SELECT month, rev,
2 LAG(rev) OVER (ORDER BY month) AS prev_rev,
3 SUM(rev) OVER (ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
4→FROM monthly_sales;
Live Table State · 1. Load monthly_sales (ordered by month)3 rows
monthrev
2026-09100
2026-10150
2026-11200
What the DB engine just did: 3 months of revenue data ordered chronologically.

4. Quick Check Your Understanding

Module 6.3 Quick Quiz

Q1.What does LAG(revenue, 1) return for the very first row in a partition when no default value is provided?
Q2.Which frame clause computes a 3-day rolling average including today and the previous 2 days?

Keep Exploring: Related Lessons & Tools

All Courses →