Offset Functions (LAG/LEAD): Concept
Module: Window Functions
Think of LAG and LEAD as time machines for your data. LAG lets you peek at previous rows ("What was the sales figure last month?"), while LEAD lets you peek at future rows ("What will be the next quarter's target?"). They're like having a conversation with your data across time - comparing today's performance to yesterday's, or checking if next week's forecast looks realistic. Instead of complex self-joins that make your head spin, these functions give you simple, readable time-based comparisons. Perfect for answering "How did we do compared to last time?" questions.
**
**LAG() - The Time Traveler Looking Back:**
LAG accesses values from previous rows in the result set, ordered by your specified columns.
```sql
-- Basic LAG syntax
LAG(column_name, offset, default_value) OVER (ORDER BY sort_column)
-- Example: Monthly revenue comparison
SELECT
month,
revenue,
LAG(revenue, 1, 0) OVER (ORDER BY month) as prev_month_revenue,
revenue - LAG(revenue, 1, 0) OVER (ORDER BY month) as month_over_month_change
FROM monthly_sales;
```
**LAG Parameters Explained:**
- **column_name**: Which column's value to retrieve from previous row
- **offset**: How many rows back to look (default: 1)
- **default_value**: What to return when no previous row exists (default: NULL)
**LAG Use Cases:**
- ✅ **Growth calculations**: Revenue vs last month, users vs last quarter
- ✅ **Trend analysis**: Stock prices, website traffic, sales performance
- ✅ **Change detection**: Identify when metrics increased/decreased
- ✅ **Period comparisons**: This year vs last year, today vs yesterday
**LEAD() - The Fortune Teller Looking Forward:**
LEAD accesses values from subsequent rows, perfect for forecasting and forward-looking analysis.
```sql
-- Basic LEAD syntax
LEAD(column_name, offset, default_value) OVER (ORDER BY sort_column)
-- Example: Inventory planning
SELECT
week,
current_inventory,
LEAD(projected_demand, 1, 0) OVER (ORDER BY week) as next_week_demand,
current_inventory - LEAD(projected_demand, 1, 0) OVER (ORDER BY week) as surplus_deficit
FROM inventory_forecast;
```
**LEAD Use Cases:**
- ✅ **Forecasting**: Compare current to projected future values
- ✅ **Planning**: Inventory needs, staffing requirements