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

Row Offsets: LAG and LEAD

Lesson preview5 hands-on exercises readySQL Course · Module 13 — Window Functions

Compare current rows against preceding or following rows to compute deltas and trends.

What you'll learn in this lesson

  • Peek into the previous (LAG) or next (LEAD) row of the same window without resorting to self-join lenses.
  • Specify offset (n) and default value (default) to handle partition borders without unwanted NULL.
  • Check the sliding frame (ROWS BETWEEN ... PRECEDING AND CURRENT ROW) for moving averages and time variations.

Overview

Historical series of prices, orders and reviews almost always require comparisons with respect to the previous or subsequent point: "how much has the price changed compared to the previous launch?" or "what rating did the same customer leave on the next order?". LAG and LEAD resolve these comparisons in a single ordered pass.

Activate LEAD with frame moving2 or switch to AVG and SUM by clicking various rows: highlight badges show live which previous/next row (or which 2-element interval) feeds each calculation!

Sections covered in this lesson

  1. 11. Mental Model: Offset Navigation in the Window
  2. 22. Progressive & Annotated Examples
  3. 33. Interactive Laboratory: Sliding Window moving2, LAG and LEAD
  4. 44. Diagnostic Verification (Quiz)
  5. 55. Progressive Practical Laboratory
Pro Lesson · Module 13 — Window Functions

Unlock "Row Offsets: LAG and LEAD" and the full SQL Course curriculum

Compare current rows against preceding or following rows to compute deltas and trends.

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.