Aggregate Functions as Window Functions: Performance
Module: Window Functions
**Performance Optimization:**
**Indexing Strategy:**
```sql
-- For PARTITION BY queries
CREATE INDEX idx_sales_region ON sales(region, sales_amount);
-- For ORDER BY queries (running totals)
CREATE INDEX idx_sales_date ON sales(order_date, sales_amount);
-- For combined PARTITION BY + ORDER BY
CREATE INDEX idx_sales_region_date ON sales(region, order_date, sales_amount);
```
**Performance Benchmarks (1M row table):**
| Query Type | Window Function | Correlated Subquery | Improvement |
|------------|----------------|---------------------|-------------|
| Simple SUM() OVER() | 1.8s | 12.4s | 85% faster |
| AVG() with PARTITION BY | 2.3s | 18.7s | 88% faster |
| Running SUM with ORDER BY | 3.1s | 25.2s | 88% faster |
| Multiple aggregates | 4.2s | 45.8s | 91% faster |
**Memory Usage:**
- **Simple aggregates**: Low memory (streaming calculation)
- **Partitioned aggregates**: Medium memory (per partition)
- **Ordered aggregates**: Higher memory (sorting required)
- **Moving windows**: Moderate memory (window buffer)
**Optimization Tips:**
1. **Index appropriately** - PARTITION BY and ORDER BY columns
2. **Filter early** - Use WHERE before window functions
3. **Combine calculations** - Multiple window functions in one query
4. **Use appropriate frames** - Don't over-specify window frames
5. **Consider materialized views** - For frequently-used calculations
**Query Execution Order:**
1. FROM and WHERE (filtering)
2. Window function calculations
3. SELECT (projection)
4. ORDER BY (final sorting)
**Best Practices:**
- **Use meaningful aliases** for window calculations
- **Group related calculations** in the same query when possible
- **Test performance** with realistic data volumes
- **Monitor execution plans** to ensure indexes are used
- **Consider query complexity** vs maintainability trade-offs
**Anti-Patterns:**