Coding
AI Prompt for Optimizing SQL Queries
Speed up slow SQL with this AI prompt: execution-plan analysis, index recommendations, and a rewritten query that returns the same results faster.
The prompt
Role: You are a database performance consultant who makes slow queries fast without changing their results. Context: Dialect: [DIALECT]. The slow query: [SLOW_QUERY]. It takes [EXECUTION_TIME] on [TABLE_SIZES]. Schema and existing indexes: [SCHEMA_AND_INDEXES]. Execution plan: [EXPLAIN_OUTPUT]. Task: 1) Diagnose from the plan: what is the expensive step (seq scan, nested loop, sort spill, correlated subquery)? 2) Rewrite the query for speed while returning IDENTICAL results — prove equivalence by explaining the transformation. 3) Recommend specific indexes (exact CREATE INDEX statements) with the reasoning for each. 4) Estimate the expected improvement and state what to measure to confirm it. Format: Diagnosis first, then the rewritten query, then index recommendations, then how to verify. Ask the AI to predict the new execution plan in words before you apply the changes, then compare with the actual EXPLAIN afterward. Matching prediction to reality is how you build a reliable intuition for query plans. Constraints: Results must be identical — no changing semantics for speed. Prefer index and rewrite fixes over hardware or config changes. Warn if the rewrite trades write performance for read performance.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[DIALECT] [SLOW_QUERY] [EXECUTION_TIME] [TABLE_SIZES] [SCHEMA_AND_INDEXES] [EXPLAIN_OUTPUT]
Example input
DIALECT=PostgreSQL, SLOW_QUERY=SELECT with 3 JOINs and a correlated subquery taking 8s on 2M rows, SCHEMA=tables + indexes listed, PLAN=EXPLAIN ANALYZE output pasted
How to use this prompt
Paste EXPLAIN/EXPLAIN ANALYZE output — it is the single most valuable input for optimization. Include table sizes and existing indexes.
Tips for the best results
- Always test the rewritten query returns identical results on a data sample first.
- Ask which index helps which part of the query — understanding beats copy-paste.
- Re-run EXPLAIN after applying changes and ask the AI to confirm the plan improved.
Frequently asked questions
Can it optimize without seeing my data?
It finds the classic culprits (correlated subqueries, missing indexes, functions on indexed columns). Paste EXPLAIN output for a precise diagnosis.
Will the rewritten query always be faster?
On your data and indexes, almost always — but verify with EXPLAIN ANALYZE. Data distribution surprises even experts, so the prompt includes a verification step.