Module lessons (3/4)
LAG, LEAD, and Running Totals
Compare each row to its neighbors and accumulate cumulative totals.
What you'll learn in this lesson
- Compare each row with the previous (
LAG) or next (LEAD) within your partition. - Construct running totals and moving averages with
SUM(...) OVER (PARTITION BY ... ORDER BY ...). - Distinguish when
SUM() OVERcalculates the cumulative total (withORDER BY) versus the partition total (withoutORDER BY).
Overview
Analysis of times between consecutive orders, month-on-month percentage changes and progressive balances on the current account: before window functions these queries required complex self-joins. With LAG, LEAD and SUM() OVER they are expressed in a single clean scan.
Click on any row of the table to see exactly which rows enter the calculation: try changing the function between LAG, LEAD and SUM with frames running (cumulative), moving2 or entire (entire partition)!
Sections covered in this lesson
- 11. Mental Model: Moving Windows and the Effect of
ORDER BY - 22. Progressive & Annotated Examples
- 33. Interactive Laboratory: Cumulative Windows,
LAGandLEAD - 44. Diagnostic Verification (Quiz)
- 55. Progressive Practical Laboratory
Unlock "LAG, LEAD, and Running Totals" and the full SQL Course curriculum
Compare each row to its neighbors and accumulate cumulative totals.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in SQL Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.