MODULE 6 OF 8: WINDOW FUNCTIONS • LESSON 3 OF 5~22 min read

LAG, LEAD, Running Totals and Moving Aggregates

Navigation and aggregate window functions compare rows in an ordered sequence without collapsing the result. LAG and LEAD access values from neighboring rows, running totals accumulate values through a sequence, and moving aggregates calculate over a bounded set of nearby rows. These patterns appear in month-over-month comparisons, sales reports and activity analytics.

•

Navigation and aggregate window functions compare rows in an ordered sequence without collapsing the result. LAG and LEAD access values from neighboring rows, running totals accumulate values through a sequence, and moving aggregates calculate over a bounded set of nearby rows. These patterns appear in month-over-month comparisons, sales reports and activity analytics.

Key Takeaways at a Glance:

  • •LAG(col, N) fetches values from N rows BEFORE the current row; LEAD(col, N) fetches values from N rows AFTER.
  • •Running totals use 'SUM(amount) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)'.
  • •Omitting the frame specification in 'OVER (ORDER BY date)' defaults to 'RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW', which combines tied rows!
  • •Moving averages specify a sliding frame: 'ROWS BETWEEN 2 PRECEDING AND CURRENT ROW' for a 3-point moving average.

In Simple Words (The Mental Model)

LAG and LEAD let you peek into neighboring rows without joining the table to itself. LAG looks backwards at yesterday's number to see if sales went up or down. A running total is like a piggy bank: as each day's earnings come in, they get added to the running total balance.

Real-World Analogy

Think of an odometer on a car. Every mile you drive today gets added to the total miles driven in the car's lifetime (Running Total). If you check your gas receipt from your last fill-up to compare gas prices between then and now, you are using LAG.

Foundational Principles

Core Concept Breakdown

Essential database invariants, relational theory, and execution behavior.

1LAG and LEAD look backward or forward

LAG reads a value from a preceding row in the window order; LEAD reads from a following row. Both use ORDER BY inside OVER to define which row is previous or next. If no neighboring row exists, the result is NULL unless a default value is supplied. They do not mean previous or next calendar period unless the data contains and correctly orders those periods.

Free Preview Limit Reached (2/2 Lessons Used)

Sign In to Unlock Full Lesson Content

Visitors are limited to 2 free preview lessons. Create a free StudyVex account to unlock all 38 comprehensive theory chapters, runnable query walkthroughs, visual input & result tables, and interactive placement quizzes.