Advanced Analytics Functions: Performance
Module: Window Functions
**Performance Optimization Strategies:**
**Indexing for Analytics:**
- Index all ORDER BY columns used in window functions
- Composite indexes for PARTITION BY + ORDER BY combinations
- Consider covering indexes for frequently accessed columns
- Example: CREATE INDEX idx_sales_date_amount ON sales(date, amount);
**Query Structure:**
- Use CTEs to break complex calculations into logical steps
- Avoid deeply nested window functions
- Pre-filter data with WHERE clauses before analytics
- Consider materialized views for frequently accessed complex calculations
**Memory Management:**
- Statistical functions require full dataset scan
- PERCENTILE_CONT needs to sort entire partition
- Monitor work_mem settings for large datasets
- Consider partitioning large tables by date/category
**Execution Plan Analysis:**
- Use EXPLAIN ANALYZE to identify bottlenecks
- Look for expensive Sort operations
- WindowAgg nodes show window function processing
- Hash Aggregate indicates grouping operations
**Best Practices:**
- Limit data range with date filters when possible
- Use appropriate precision for PERCENTILE_CONT
- Cache results in materialized views for dashboards
- Test performance with production-sized datasets
**Example Optimization:**
```sql
-- Slow: No indexes, full table scan
SELECT CORR(sales, marketing_spend) FROM monthly_data;
-- Fast: With proper index
CREATE INDEX idx_monthly_sales_marketing ON monthly_data(sales, marketing_spend);
SELECT CORR(sales, marketing_spend) FROM monthly_data;
-- Optimal: Pre-filtered with materialized view
CREATE MATERIALIZED VIEW recent_correlations AS
SELECT
department,
CORR(sales, marketing_spend) as sales_marketing_corr,
STDDEV(sales) as sales_volatility
FROM monthly_data