Offset Functions (LAG/LEAD): Performance
Module: Window Functions
**Performance Benchmarks:**
| Query Type | Self-Join Approach | LAG/LEAD Approach | Improvement |
|------------|-------------------|-------------------|-------------|
| Simple period comparison | 5.2s | 0.8s | 85% faster |
| Multi-period analysis | 18.7s | 2.1s | 89% faster |
| Partitioned comparisons | 25.3s | 3.4s | 87% faster |
**Indexing Strategy:**
```sql
-- For ORDER BY date queries
CREATE INDEX idx_sales_date ON daily_sales(date);
-- For PARTITION BY + ORDER BY queries
CREATE INDEX idx_sales_product_date ON sales(product_id, date);
-- For complex time-series queries
CREATE INDEX idx_metrics_region_date ON metrics(region, date, metric_value);
```
**Memory Usage:**
- **LAG/LEAD**: Minimal memory overhead (just offset tracking)
- **Self-joins**: High memory usage (full table joins)
- **Window buffer**: Small buffer for offset calculations
**Optimization Tips:**
1. **Index ORDER BY columns** - Critical for performance
2. **Use appropriate offsets** - Don't look further back than needed
3. **Provide defaults** - Avoid NULL handling overhead
4. **Filter before windowing** - Use WHERE to reduce dataset size
5. **Consider partitioning** - Separate calculations per group
**Query Execution Plan:**
```sql
-- Efficient LAG query
EXPLAIN ANALYZE
SELECT date, sales, LAG(sales, 1, 0) OVER (ORDER BY date)
FROM daily_sales
WHERE date >= '2024-01-01';
-- Look for: Index Scan, Window function (not Sort if indexed properly)
```
**Best Practices:**
- **Always provide defaults** to avoid NULL complications
- **Use meaningful column aliases** (prev_month_sales vs lag_sales)
- **Index your ORDER BY columns** for optimal performance
- **Consider data types** when calculating differences
- **Handle division by zero** in percentage calculations