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_date | daily_revenue | prev_day_revenue (LAG) | DoD Revenue Diff | DoD % Growth |
|---|---|---|---|---|
| 2026-11-01 | ₹35,000.00 | NULL | NULL | NULL |
| 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:
LAG(col, offset, default)
Definition: Accesses data from a preceding row at a specified physical offset within the partition without a self-join.
LAG(daily_revenue, 1, 0) OVER (PARTITION BY store_id ORDER BY order_date)
col: Column whose previous value is retrieved.offset: Number of rows back (default 1).default: Fallback value if offset falls outside partition (default NULL).
daily_revenue - LAG(daily_revenue, 1) OVER (ORDER BY sale_date)LEAD(col, offset, default)
Definition: Accesses data from a subsequent row following the current row within the partition.
LEAD(order_time, 1) OVER (PARTITION BY rider_id ORDER BY order_time)
col: Column whose future value is retrieved.offset: Number of rows ahead (default 1).
TIMESTAMPDIFF(MINUTE, delivery_time, LEAD(pickup_time) OVER (PARTITION BY rider_id ORDER BY delivery_time))FIRST_VALUE() & LAST_VALUE()
Definition: Returns the value evaluated at the first or last row of the ordered window frame.
FIRST_VALUE(price) OVER (PARTITION BY category_id ORDER BY price ASC)
col: Target column to evaluate at window boundary.
FIRST_VALUE(price) OVER (PARTITION BY category_id ORDER BY price ASC)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)
| Action | Windows | Mac |
|---|---|---|
| Execute Query | Ctrl + Enter | Cmd + 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.