Prompt Library ⚙️ Technical Optimize Slow Database Queries with AI
GPT-4o ⚙️ Technical Advanced

Optimize Slow Database Queries with AI

Diagnose and fix slow SQL queries — analyzing execution plans, identifying bottlenecks, and writing optimized versions with index recommendations.

👁 4 views ⎘ 0 copies ♥ 0 likes

The Prompt

# Optimize Slow Database Queries with AI

You are a database performance engineer specializing in [DATABASE_TYPE] optimization.

## Query Context

Database: [DATABASE_TYPE] (PostgreSQL / MySQL / SQLite / other)
Table sizes involved: [TABLE_SIZES]
Current query execution time: [CURRENT_TIME]
Target execution time: [TARGET_TIME]

Slow query:
```sql
[PASTE_QUERY_HERE]
```

Relevant schema (table definitions):
```sql
[PASTE_SCHEMA_HERE]
```

EXPLAIN output (if available):
```
[PASTE_EXPLAIN_OUTPUT]
```

## Diagnosis

**Step 1 — Identify the bottleneck:**
What is the most expensive operation in this query? (full table scan, sort, nested loop join, missing index, etc.)

**Step 2 — Analyze the EXPLAIN plan:**
Read the execution plan and identify the worst-performing nodes.

**Step 3 — Check for common anti-patterns:**
Does this query have: SELECT *, functions on indexed columns, implicit type conversions, N+1 patterns, or missing join conditions?

## Optimization

**Optimized query:**
Write the improved version with explanation of each change.

**Index recommendations:**
Write the exact CREATE INDEX statements that would help this query and explain why.

**Schema changes (if warranted):**
Are there denormalization, partitioning, or materialized view opportunities for [TABLE_SIZES]?

## Verification

Provide the EXPLAIN statement to run on the optimized query to confirm improvement.

📝 Fill in the blanks

Replace these placeholders with your own content:

[DATABASE_TYPE]
[TABLE_SIZES]
[CURRENT_TIME]
[TARGET_TIME]
[PASTE_QUERY_HERE]
[PASTE_SCHEMA_HERE]
[PASTE_EXPLAIN_OUTPUT]

How to use this prompt

1
Copy the prompt

Click "Copy Prompt" above to copy the full prompt text to your clipboard.

2
Replace the placeholders

Swap out anything in [BRACKETS] with your specific details.

3
Paste into GPT-4o

Open your preferred AI assistant and paste the prompt to get started.