Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In relational databases, rows are theoretically unordered sets. However, real-world business intelligence often depends on inter-row comparisons:
Before window functions, answering these questions required costly self-joins with complex offset conditions. The LAG() and LEAD() positional value functions allow you to peer backward or forward across rows with zero self-joins.
LAG(expr [, offset [, default]]): Accesses data from a preceding row at a specified physical offset prior to the current row within the partition.LEAD(expr [, offset [, default]]): Accesses data from a succeeding row at a specified physical offset after the current row within the partition.Both functions accept three arguments:
expr: The column or expression to retrieve.offset (Optional, Default: 1): The number of rows back (for LAG) or forward (for LEAD) to inspect.default (Optional, Default: NULL): The fallback value if the offset reaches outside the partition boundary.Suppose we have monthly revenue data:
Calculating prior month revenue, net difference, and percentage growth:
| month_id | revenue | prior_month_revenue | mom_dollar_change | mom_growth_pct |
|---|---|---|---|---|
| 1 | 10000.00 | 0.00 | 0.00 | NULL |
| 2 | 12000.00 | 10000.00 | +2000.00 | +20.00% |
| 3 | 11500.00 | 12000.00 | -500.00 | -4.17% |
| 4 | 15000.00 | 11500.00 | +3500.00 | +30.43% |
LEAD() functions identically to LAG(), but looks forward:
MySQL 8.0 also provides:
FIRST_VALUE(expr): Returns the value from the first row of the window frame.LAST_VALUE(expr): Returns the value from the last row of the window frame (requires careful frame specification like ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING).Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Ranking Functions: ROW_NUMBER, RANK, DENSE_RANK | ACID Properties in Relational Databases |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.