LEAD/LAG — Complete Guide
LEAD/LAG — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MySQL Tutorial on Toolliyo Academy.
On this page
MySQL Tutorial · Lesson 39 of 100
LEAD/LAG
Basics ✓ → Advanced
Advanced · 2 — Production · ~6 min · MySQL — Functions & Window Functions
What is this?
LAG reads a previous row; LEAD reads the next row within the window partition. Offset and default handle missing neighbors.
Why should you care?
Compare each day’s revenue to yesterday for growth % on a fintech dashboard — LAG avoids self-join pain.
See it live — copy this example
Run in MySQL Workbench or the mysql CLI.
SELECT DATE(placed_at) AS d,
SUM(total_inr) AS day_revenue,
LAG(SUM(total_inr)) OVER (ORDER BY DATE(placed_at)) AS prev_day,
SUM(total_inr) - LAG(SUM(total_inr)) OVER (ORDER BY DATE(placed_at)) AS delta_inr
FROM orders
GROUP BY DATE(placed_at);
What happened?
- Daily revenue ordered by date.
- LAG pulls previous day’s sum into same row.
- delta_inr is day-over-day change without correlated subquery.
Practice next
- Insert orders across 5 distinct dates.
- Run query; verify delta on row 2 manually.
- Use LEAD for next_day preview column.
- LAG with third arg default 0 for first row.
- PARTITION BY city via JOIN for city-level deltas.
Remember
LAG = look back; LEAD = look ahead. ORDER BY defines row sequence. Great for period-over-period metrics.
DataFlow GMV alert
Alert fires when delta_inr drops 30% vs LAG day — ops investigates pipeline.
Outcome: Incidents caught before weekly review.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!