Mastering MySQL for Data AnalystsLesson 31 of 42
Lesson 31 of 42

Value Window Functions: LAG, LEAD, FIRST_VALUE & LAST_VALUE in MySQL 8.0

Overview & Learning Objectives

Time-series analysis and cohort behavior analysis require comparing a row's metric with the preceding or subsequent row—such as calculating Month-over-Month (MoM) revenue growth or tracking the time elapsed between customer orders. MySQL 8.0 provides Value Window functions: `LAG()` (retrieves previous row), `LEAD()` (retrieves next row), `FIRST_VALUE()`, and `LAST_VALUE()`, eliminating the need for slow, fragile self-joins.

  • Calculate Day-over-Day (DoD) and Month-over-Month (MoM) revenue variance using `LAG()`.
  • Track customer repeat purchase latency and session idle times using `LEAD()`.
  • Anchor baseline metrics across partitions using `FIRST_VALUE()`.

Industry Standard

Standard: Financial analysts at Goldman Sachs and Stripe use `LAG()` to compute historical portfolio returns and continuous growth metrics across millions of trade ticks.

Real-World Example: ScoopCraft Day-over-Day (DoD) Revenue Variance

ScoopCraft calculates daily sales variance and percentage growth compared to the previous calendar day.

order_datedaily_revenueprev_day_revenue (LAG)DoD Revenue DiffDoD % Growth
2026-11-01₹35,000.00NULLNULLNULL
2026-11-02₹42,000.00₹35,000.00+₹7,000.00+20.0%
2026-11-03₹38,000.00₹42,000.00-₹4,000.00-9.5%
2026-11-04₹50,000.00₹38,000.00+₹12,000.00+31.6%

Functions & Syntax Covered in this Chapter

Here is the definition, execution syntax, parameter breakdown, and real-world business example for each function/syntax covered in this chapter:

Feature 1

LAG(col, offset, default)

Definition: Accesses data from a preceding row at a specified physical offset within the partition without a self-join.

Syntax / Code Pattern:
LAG(daily_revenue, 1, 0) OVER (PARTITION BY store_id ORDER BY order_date)
Parameters Breakdown:
  • col: Column whose previous value is retrieved.
  • offset: Number of rows back (default 1).
  • default: Fallback value if offset falls outside partition (default NULL).
Real-World Example (Day-over-Day (DoD) Revenue Variance):
Problem / Scenario: Compare today's revenue against yesterday's revenue to compute growth percentage.
SQL Query / Expression: daily_revenue - LAG(daily_revenue, 1) OVER (ORDER BY sale_date)
Result: Today: ₹15,000, Prev: ₹12,000 -> Diff: +₹3,000 (+25%)
Why it works: Pulls previous day revenue onto the current row for direct subtraction.
Feature 2

LEAD(col, offset, default)

Definition: Accesses data from a subsequent row following the current row within the partition.

Syntax / Code Pattern:
LEAD(order_time, 1) OVER (PARTITION BY rider_id ORDER BY order_time)
Parameters Breakdown:
  • col: Column whose future value is retrieved.
  • offset: Number of rows ahead (default 1).
Real-World Example (Rider Delivery Idle Time):
Problem / Scenario: Calculate minutes elapsed between current delivery completion and next delivery pickup.
SQL Query / Expression: TIMESTAMPDIFF(MINUTE, delivery_time, LEAD(pickup_time) OVER (PARTITION BY rider_id ORDER BY delivery_time))
Result: Current delivery ends 14:10, next pickup 14:25 -> 15 min idle
Why it works: Looks ahead to the next order row to compute idle intervals.
Feature 3

FIRST_VALUE() & LAST_VALUE()

Definition: Returns the value evaluated at the first or last row of the ordered window frame.

Syntax / Code Pattern:
FIRST_VALUE(price) OVER (PARTITION BY category_id ORDER BY price ASC)
Parameters Breakdown:
  • col: Target column to evaluate at window boundary.
Real-World Example (Variance from Category Baseline):
Problem / Scenario: Display each product's price alongside the cheapest entry-level item in that category.
SQL Query / Expression: FIRST_VALUE(price) OVER (PARTITION BY category_id ORDER BY price ASC)
Result: Product: ₹350, Category_Baseline: ₹120
Why it works: Retrieves the lowest price in the category partition onto every member row.

Common Mistakes & Limitations

  • Omitting the `ORDER BY` clause inside the `OVER()` specification of `LAG()` or `LEAD()`, causing non-deterministic offsets.
  • Using `LAST_VALUE()` without specifying `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`, causing it to mistakenly return the current row.

Keyboard Shortcuts (MySQL Workbench)

ActionWindowsMac
Execute QueryCtrl + EnterCmd + Enter

Pro Tips & Modern Best Practices

  • In MySQL 8.0, calculate time between orders using `TIMESTAMPDIFF(DAY, LAG(order_date) OVER(PARTITION BY cust_id ORDER BY order_date), order_date)`.
  • Always specify an explicit default value in `LAG(val, 1, 0)` if performing mathematical division to avoid unexpected NULL outputs.