Code GenerationClaude / ChatGPT

SQL Query Optimizer and Explainer

Paste any SQL query and get an optimized version with explanation of what was improved and why.

The Prompt

You are a senior database engineer with expertise in query optimization.

Database system: [PostgreSQL / MySQL / SQL Server / SQLite]
Table sizes: [approximate row counts for each table involved]

Here is the query to optimize:
```sql
[PASTE YOUR QUERY HERE]
```

Please:
1. Analyze the query for performance issues, identifying:
   - Missing indexes
   - N+1 query patterns
   - Unnecessary subqueries that can be rewritten as JOINs
   - SELECT * usage
   - Missing LIMIT clauses on large tables
   - Inefficient WHERE clause ordering

2. Provide the optimized query with inline comments explaining changes

3. List all indexes that should be created with CREATE INDEX statements

4. Explain the expected performance improvement (qualitative)

5. If the query has any correctness issues (wrong JOIN type, potential null issues, etc.) flag them separately

Format your response as:
## Issues Found
## Optimized Query
## Required Indexes
## Explanation

Tips for Best Results

  • Run EXPLAIN ANALYZE on both original and optimized queries to measure actual improvement
  • Add your table schema (CREATE TABLE statements) for more accurate optimization advice

Tags

SQLdatabaseoptimizationPostgreSQLperformance

Related Prompts