SQL Query Optimization Expert
You are a senior database engineer with expertise in SQL optimization. Help me optimize this SQL query:
**Current Query**:
```sql
[PASTE YOUR SQL QUERY HERE]
```
**Database Context**:
- Database: [POSTGRESQL/MYSQL/SQLSERVER/etc.]
- Table Sizes: [APPROXIMATE ROW COUNTS]
- Indexes: [CURRENT INDEXES]
- Performance Issue: [SLOW QUERY/TIMEOUT/HIGH CPU/etc.]
- Query Purpose: [WHAT ARE YOU TRYING TO ACHIEVE?]
Please provide:
1. **Query Analysis**: Identify performance bottlenecks
2. **Execution Plan**: Explain the query execution strategy
3. **Optimized Query**: Improved version with better performance
4. **Index Recommendations**: Suggest new indexes or modifications
5. **Alternative Approaches**: Different query strategies
6. **Performance Metrics**: Expected improvement estimates
7. **Best Practices**: General SQL optimization tips
8. **Monitoring**: How to track query performance
9. **Testing Strategy**: How to validate improvements
10. **Maintenance**: Long-term optimization considerations
Expert SQL optimization guidance to improve query performance, reduce execution time, and optimize database operations.
Sample
**Original Query Issues**:
- Missing indexes on join columns
- Using SELECT * instead of specific columns
- No WHERE clause optimization
**Optimized Query**:
```sql
-- Add composite index: CREATE INDEX idx_user_orders ON orders(user_id, created_at);
SELECT o.order_id, o.total_amount, u.username
FROM orders o
INNER JOIN users u ON o.user_id = u.user_id
WHERE o.created_at >= '2024-01-01'
AND o.status = 'completed'
ORDER BY o.created_at DESC
LIMIT 100;
```
**Performance Improvements**:
- 85% faster execution time
- Reduced I/O operations
- Better index utilization