20 of the best prompts for batching database queries efficiently, step by step across 4 stages. Works with ChatGPT, Claude, and Gemini.
20 of the best prompts for batching database queries efficiently, step by step across 4 stages. Works with ChatGPT, Claude, and Gemini.
Published June 28, 2026
Claude Code sometimes generates database access code that runs queries inside a loop, leading to inefficient N+1 query problems. This results in performance bottlenecks and increased load times. These prompts help developers identify and correct the issue, ensuring optimal database interactions. Built across 4 distinct stages covering Diagnose the Wall, Isolate and Fix, Verify the Resolution and more, this guide gives you one expert prompt per step so you never have to write from scratch or guess what the AI needs. The prompts work in ChatGPT, Claude, and Gemini and are designed to get usable output on the first try.
Identify if queries are being run inside loops instead of being batched.
Check Loop Queries
Please analyze the codebase for instances where database queries are executed inside loops. For each occurrence, provide the file names and line numbers where these queries are found. Additionally, explain the potential performance implications of executing queries within loops and suggest best practices for optimizing these queries to improve overall efficiency.
Review Query Patterns
Please review the recent code changes and identify any patterns where queries are executed repeatedly within loops. For each identified pattern, provide details on the specific functions or methods involved, including the frequency of execution and any potential performance implications. Additionally, suggest possible optimizations or refactoring strategies to improve efficiency in these areas. Format your findings in a clear report that includes code snippets for illustration.
Identify N+1 Scenarios
Please analyze the provided code and identify any potential N+1 query scenarios. For each scenario, list the specific sections of code where this pattern is evident, including line numbers and a brief description of the context. Additionally, suggest possible solutions or optimizations to address these issues and improve the overall efficiency of the code. Format your findings in a clear and organized manner, making it easy to understand the implications of each identified scenario.
Analyze Database Access
Analyze the database access code provided. Determine whether the queries are being executed individually or in batches, and explain the implications of each approach on performance and efficiency. Include specific examples from the code to support your analysis, and summarize your findings in a clear and concise format. Additionally, suggest any potential improvements or best practices for optimizing database access based on your analysis.
Evaluate Query Efficiency
Please evaluate the efficiency of the current database queries in my system. Identify any queries that are executed multiple times unnecessarily and provide a detailed report on their locations within the codebase, along with the frequency of each query's execution. Additionally, suggest potential optimizations or alternatives for these queries to improve overall performance. Format the findings in a clear and organized manner, highlighting the most critical issues first.
Focus on modifying the code to batch queries instead of running them inside loops.
Refactor Loop Queries
Refactor the following code to optimize database queries by batching those that are currently executed inside loops. Ensure that the new implementation minimizes the number of database calls and improves performance. Provide the updated code snippets along with a brief explanation of the changes made and how they enhance efficiency. The original code is as follows: [INSERT ORIGINAL CODE HERE].
Implement Query Batching
Revise the existing code to implement query batching for the identified N+1 scenarios. Provide the updated code along with a detailed explanation of the changes made, including how the batching improves performance and reduces the number of database calls. Additionally, outline any potential trade-offs or considerations that should be kept in mind when using query batching in this context. Ensure the explanation is clear and concise, suitable for someone with a basic understanding of coding and database interactions.
Optimize Database Calls
Please optimize the database calls in the existing code by combining them into a single query wherever possible. Show me the revised code along with a detailed explanation of the improvements made, including how this optimization enhances performance, reduces latency, and minimizes resource usage. Additionally, outline any potential trade-offs or considerations that should be kept in mind with this new approach. Ensure the explanation is clear and easy to understand for someone with a basic knowledge of database management.
Use Efficient Query Methods
Identify inefficient query methods in the provided code and suggest more efficient alternatives that support batching. For each method you replace, present the updated code along with a clear rationale explaining why the new method is more efficient. Additionally, highlight any potential performance improvements and considerations to keep in mind when implementing these changes.
Consolidate Query Logic
Please consolidate the query logic in the provided code to minimize the number of database calls. Refactor the code accordingly and present the updated version. Additionally, explain the steps you took during the consolidation process, including the reasoning behind the changes made and how they improve efficiency. Ensure that the explanation is clear and detailed, highlighting any specific techniques or methods used in the refactoring.
Ensure that the changes have resolved the N+1 query problem and improved performance.
Test Query Performance
Please run performance tests on the updated code to verify whether the N+1 query problem has been resolved. Provide a detailed report of the test results, including specific performance metrics such as response time, resource usage, and any changes in database load before and after the update. Additionally, include any observations or recommendations based on the performance data collected. Format the results in a clear and organized manner for easy review.
Confirm Query Batching
Please verify that the queries are batched correctly and not executed within loops. Provide a detailed confirmation of the batching process, including any relevant output or metrics that illustrate the performance improvements achieved. Additionally, explain how this change impacts overall efficiency and any potential issues that may arise from this new batching approach.
Validate Code Changes
Please validate the recent code changes made to address the N+1 query issue. Outline the specific steps taken during the validation process, including any tests or benchmarks used to assess performance improvements. Provide a detailed report on the outcomes of the validation, highlighting any remaining issues or areas for further optimization. Include recommendations for future code changes or monitoring strategies to prevent similar issues from arising.
Review Execution Logs
Please analyze the execution logs from the database and confirm whether the number of queries has decreased compared to previous logs. Provide a detailed summary of your findings, including specific metrics on query counts, any patterns observed in the execution times, and potential reasons for any changes noted. Additionally, include recommendations for further optimization if applicable, and format the results in a clear report structure with headings for each section.
Assess System Load
Please assess the system load before and after implementing the changes to evaluate their impact on efficiency. Provide a detailed report that includes metrics such as CPU usage, memory consumption, and response times for both scenarios. Compare the findings and highlight any significant improvements or areas that still require attention. Format the results in a clear table for easy reference, and include a summary of your conclusions regarding the overall system performance.
Create reusable artefacts to prevent future occurrences of the N+1 query problem.
Create CLAUDE.md Rule
Please create a new rule for CLAUDE.md that addresses the prevention of N+1 queries. The rule should include a clear explanation of what N+1 queries are, why they can be problematic, and specific guidelines on how to avoid them in code. Additionally, provide example code snippets that illustrate both the incorrect implementation leading to N+1 queries and the corrected version that adheres to the new rule. Format the rule in a way that is easy to understand and implement for developers.
Add Code Comment
Please add a code comment in the relevant sections of the code to remind developers about the importance of batching queries. The comment should clearly explain why batching is beneficial, including its impact on performance and resource management. Use a concise format that can be easily understood by other developers. Provide the exact text of the comment that should be inserted.
Develop Checklist
Please develop a comprehensive checklist for session openers that includes specific items to ensure effective query batching. The checklist should cover essential aspects such as verifying the format of the queries, confirming the number of queries being batched, ensuring that the queries are optimized for performance, and checking for any potential errors or conflicts. Additionally, include a section for best practices in session management that can help prevent recurrence of issues. Format the checklist in a clear, organized manner with bullet points for easy reference.
Establish Naming Convention
Define a comprehensive naming convention for functions that handle batched queries in a programming context. The convention should include guidelines on how to structure function names, such as using prefixes or suffixes to indicate the type of operation (e.g., "batch" or "query"), and how to incorporate relevant parameters or context into the name. Provide at least five examples of function names that adhere to this convention, explaining the rationale behind each name and how it reflects the intended functionality. Additionally, outline any best practices for maintaining consistency in naming across the codebase.
Implement Project Guard
Help me design a project guard that automatically detects and flags N+1 query patterns in a software application. The guard should monitor database queries in real-time, identify instances where multiple queries are executed for a single operation, and provide alerts or reports on these occurrences. Describe the specific functionality of the guard, including how it will log detected patterns, the criteria for flagging a query as an N+1 issue, and any recommendations it will provide for optimization. Additionally, outline the integration process with existing systems and any potential performance impacts to consider.
Claude Code may generate N+1 queries due to its autonomous nature and lack of context awareness in large codebases. It executes tasks based on immediate instructions without always optimizing for batch processing.
Include specific rules in the CLAUDE.md file to guide Claude Code in batching queries. Regularly update and review these rules to align with best practices.
Common signs include increased database load, slow response times, and repeated query execution patterns in logs. Identifying these early can help mitigate performance issues.
While Claude Code can assist in identifying and refactoring code, it requires explicit instructions to implement batching. Use prompts to guide it through the process.
Combine Claude Code with performance monitoring tools and database profiling utilities to gain insights into query performance and optimize accordingly.
AI Prompts for Batch Database Query Optimization
The tool is generating database access code that runs queries inside a loop, leading to inefficient N+1 query problems.
See promptsAI Prompts for Batch Database Query Optimization
The AI is generating database access code that runs queries inside a loop, leading to inefficient N+1 query problems.
See promptsAI Prompts for Batching Database Queries Efficiently
Cursor generates database access code that runs queries inside loops, leading to inefficient N+1 query problems.
See prompts