Skip to main content
Module 7 · Lesson 3 of 427/57 in the course~15 min
Module lessons (3/4)

LAG, LEAD, and Running Totals

Lesson preview5 hands-on exercises readySQL Course · Module 7 — Advanced Analytics

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() OVER calculates the cumulative total (with ORDER BY) versus the partition total (without ORDER 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

  1. 11. Mental Model: Moving Windows and the Effect of ORDER BY
  2. 22. Progressive & Annotated Examples
  3. 33. Interactive Laboratory: Cumulative Windows, LAG and LEAD
  4. 44. Diagnostic Verification (Quiz)
  5. 55. Progressive Practical Laboratory
Pro Lesson · Module 7 — Advanced Analytics

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.