Running Totals & Moving Averages: Performance
Module: Window Functions
**Performance Optimization:**
**Indexing Strategy:**
```sql
-- For ORDER BY date queries
CREATE INDEX idx_sales_date ON daily_sales(date, sales_amount);
-- For PARTITION BY + ORDER BY queries
CREATE INDEX idx_sales_category_date ON sales(category, date, amount);
```
**Performance Benchmarks (1M row time series):**
| Calculation Type | Execution Time | Memory Usage |
|------------------|----------------|---------------|
| Simple running total | 2.1s | 80MB |
| Single moving average | 2.8s | 120MB |
| Multiple moving averages | 4.2s | 180MB |
| Partitioned calculations | 5.1s | 220MB |
**Memory Usage by Window Size:**
| Window Size | Memory Impact | Use Case |
|-------------|---------------|----------|
| Running total | Low | Cumulative metrics |
| 7-day MA | Low | Weekly trends |
| 30-day MA | Medium | Monthly trends |
| 365-day MA | High | Annual trends |
**Optimization Techniques:**
1. **Index ORDER BY columns** - Critical for performance
2. **Combine calculations** - Multiple window functions in one query
3. **Use appropriate data types** - DECIMAL for financial data
4. **Filter before windowing** - Use WHERE to reduce dataset
5. **Consider materialized views** - For frequently-used calculations
**Query Execution Tips:**
- **Batch multiple calculations** together for efficiency
- **Use consistent ORDER BY** across window functions
- **Monitor memory usage** for large windows
- **Test with realistic data volumes** before production
**Best Practices:**
- **Use meaningful aliases** (ytd_revenue vs sum_revenue)
- **Document window sizes** in comments
- **Handle edge cases** (first few rows in moving averages)
- **Consider business calendar** (exclude weekends/holidays)
- **Validate results** with known calculations
**Anti-Patterns:**