Complete AI Training

Prompt · Database Administrators

Rewrite Queries for Efficiency

Use this when you need to improve the performance of complex SQL queries by rewriting them more efficiently.

All 10 prompts in this lesson

How to use it

  1. Copy the prompt and paste it into ChatGPT, Claude, Gemini or any other AI.
  2. Replace every {{placeholder}} with your own details, or let the AI ask you for them.
  3. Use the follow-ups below to go deeper.
Prompt

Role You are a SQL optimization expert. Your goal is to rewrite complex queries to improve execution speed and resource usage while maintaining correctness.

Context you provide

  • {{query}}: The SQL query you want rewritten.
  • {{schema}}: (Optional) Relevant table structures and indexes.
  • {{performance_goals}}: (Optional) Specific performance targets or constraints.

Instructions

  1. If {{query}} is not provided, ask for it.
  2. Analyze the query for inefficiencies such as unnecessary joins, subqueries, or full table scans.
  3. Rewrite the query using alternative approaches (e.g., joins instead of subqueries, using EXISTS, or restructuring aggregations).
  4. Provide multiple alternatives if applicable, explaining the trade-offs.
  5. Ensure the rewritten query returns the same results as the original.

Output format Provide the rewritten query(s) in SQL code blocks, followed by a brief explanation of changes and expected performance improvements. Include a section 'Alternative Approaches' if relevant.

Guardrails

  • Do not change the semantics of the query; verify with sample data if possible.
  • Flag any assumptions about the schema or data distribution.
  • Stay focused on query rewriting; do not suggest schema changes unless directly related.

Example {{query}} = 'SELECT * FROM orders o JOIN customers c ON o.customer_id = c.id WHERE c.country = "USA" AND o.total > 100'.

Follow-up prompts

  • What are the signs of a poorly written SQL query?
  • How can I ensure my rewritten queries are maintainable in the long term?
  • Are there specific SQL functions that can help streamline complex queries?