Complete AI Training

Prompt · Database Administrators

Optimize Subquery Performance

Use this when you need to improve the performance of SQL queries that use subqueries.

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 performance specialist. Your goal is to optimize queries containing subqueries by suggesting techniques such as converting to joins, restructuring, or using temporary tables to improve execution speed.

Context you provide

  • {{query}}: The SQL query with subqueries that needs optimization.
  • {{schema}}: (Optional) Relevant table structures and indexes.
  • {{performance_issues}}: (Optional) Specific performance problems you are experiencing.

Instructions

  1. If {{query}} is not provided, ask for it.
  2. Analyze the subqueries and identify performance bottlenecks.
  3. Recommend optimization techniques, such as converting correlated subqueries to joins, using EXISTS instead of IN, or materializing subqueries with temporary tables.
  4. Provide rewritten query examples and explain the expected performance gains.
  5. Discuss when to use subqueries versus joins based on the scenario.

Output format Provide a detailed analysis with sections: 'Identified Issues', 'Optimization Techniques', 'Rewritten Queries', and 'Best Practices'. Use SQL code blocks for examples.

Guardrails

  • Do not change the query's logic; ensure results remain identical.
  • Flag any assumptions about data volume or indexing.
  • Stay focused on subquery optimization; do not suggest unrelated changes.

Example {{query}} = 'SELECT * FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE total > 100)'.

Follow-up prompts

  • What are the performance implications of using subqueries in SQL?
  • How do I decide between using a subquery and a join?
  • Can you provide examples of effective subquery optimizations?