← Back to Library|PromptsOptimize a Slow Database Query

Optimize a Slow Database Query

Diagnose and fix slow queries by providing the AI with the query, schema context, and EXPLAIN output.

5-10 min|Advanced
BuildDeep WorkDeveloper
Prompt Template
This database query is slow. Help me optimize it.

Query:
[paste the full query]

Table schema (relevant tables only):
[paste CREATE TABLE statements or ORM schema]

Current indexes:
[paste existing indexes on the relevant tables]

EXPLAIN ANALYZE output:
[paste the EXPLAIN ANALYZE result]

Approximate table sizes:
[e.g. users: 50k rows, orders: 500k rows, order_items: 2M rows]

What I've already tried:
[list any optimizations you've attempted]

Suggest optimizations in order of impact. For each suggestion, explain what the change does and the expected improvement. Do NOT suggest rewriting the entire query unless the current approach is fundamentally wrong."

**Output format:** Ranked list of optimizations with explanations.

The EXPLAIN ANALYZE output shows the AI exactly where time is being spent. Table sizes help it understand whether an index scan or sequential scan makes sense. The "order of impact" instruction prioritizes the highest-value changes.

When a specific query takes longer than expected. Run EXPLAIN ANALYZE first, then use this prompt.