Skip to main content
coding intermediate

Optimize Database Query Performance

Use AI to analyze and optimize slow database queries. Get specific recommendations for indexing, query rewriting, and performance tuning.

Works with: chatgptclaudegemini

Prompt Template

You are a senior database performance engineer with expertise in query optimization. I need you to analyze and optimize the following database query for better performance. **Database Information:** - Database type: [DATABASE_TYPE] - Table structure and relationships: [TABLE_SCHEMA] - Current query: [CURRENT_QUERY] - Performance issues: [PERFORMANCE_ISSUES] - Data volume: [DATA_VOLUME] Please provide a comprehensive analysis including: 1. **Query Analysis**: Identify specific performance bottlenecks in the current query 2. **Optimized Query**: Provide an improved version of the query with explanations for each change 3. **Indexing Recommendations**: Suggest specific indexes that would improve performance, including composite indexes if needed 4. **Execution Plan Insights**: Explain what to look for in the execution plan and potential red flags 5. **Alternative Approaches**: If applicable, suggest completely different approaches (subqueries vs JOINs, CTEs, etc.) 6. **Scalability Considerations**: How the solution will perform as data grows 7. **Monitoring**: Key metrics to track for ongoing performance monitoring Format your response with clear sections, code blocks for SQL, and specific reasoning for each recommendation. Consider both immediate performance gains and long-term maintainability.

Variables to Customize

[DATABASE_TYPE]

The database system being used

Example: PostgreSQL 14

[TABLE_SCHEMA]

Description of relevant tables, columns, and relationships

Example: Users table (id, email, created_at), Orders table (id, user_id, total, order_date), OrderItems table (id, order_id, product_id, quantity)

[CURRENT_QUERY]

The query that needs optimization

Example: SELECT u.email, COUNT(o.id) as order_count, SUM(o.total) as total_spent FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE o.order_date >= '2023-01-01' GROUP BY u.id, u.email HAVING COUNT(o.id) > 5 ORDER BY total_spent DESC;

[PERFORMANCE_ISSUES]

Specific performance problems being experienced

Example: Query takes 45 seconds to execute, high CPU usage, frequent timeouts during peak hours

[DATA_VOLUME]

Approximate size and scale of the data

Example: 2 million users, 15 million orders, 50 million order items

Example Output

## Query Analysis The current query has several performance bottlenecks: - Missing indexes on `orders.user_id` and `orders.order_date` - Unnecessary LEFT JOIN when filtering on orders (excludes users with no orders anyway) - Inefficient GROUP BY with HAVING clause ## Optimized Query ```sql SELECT u.email, COUNT(*) as order_count, SUM(o.total) as total_spent FROM users u INNER JOIN orders o ON u.id = o.user_id WHERE o.order_date >= '2023-01-01' GROUP BY u.id, u.email HAVING COUNT(*) > 5 ORDER BY total_spent DESC; ``` ## Indexing Recommendations 1. **Composite index**: `CREATE INDEX idx_orders_date_user ON orders(order_date, user_id, total);` 2. **Covering index**: Includes `total` to avoid table lookups ## Execution Plan Insights Look for: - Index scans instead of sequential scans - Efficient join algorithms (hash join preferred for large datasets) - Avoid nested loops with large result sets ## Alternative Approaches Consider materialized views for frequently accessed aggregations: ```sql CREATE MATERIALIZED VIEW user_order_stats AS ... ``` ## Scalability Considerations The composite index will maintain performance as data grows. Consider partitioning orders table by date for datasets exceeding 100M rows. ## Monitoring Track: execution time, index usage statistics, buffer cache hit ratio, and query plan stability.

Pro Tips for Best Results

  • Always analyze the execution plan before and after optimization to verify improvements
  • Test optimizations with production-like data volumes, as small datasets can be misleading
  • Consider the trade-offs between read performance and write performance when adding indexes
  • Use database-specific features like query hints or optimizer statistics when generic optimization isn't enough
  • Monitor query performance over time as data distribution changes can affect optimal execution plans

Tags

Want 500+ Expert Prompts?

Get the Premium Prompt Pack — organized, tested, and ready to use.

Get it for $29

Related Prompts You Might Like