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
Running database queries inside a loop can lead to performance issues known as the N+1 query problem. This results in excessive database calls, slowing down the application. These prompts help developers identify and fix this issue by batching queries, improving performance and efficiency. 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 the code is executing database queries inside a loop.
Check Loop for Queries
Analyze the following code snippet for any database queries being executed inside loops: [PASTE CODE]. Identify whether these queries are causing an N+1 query problem and explain the implications of this issue on performance. Additionally, suggest potential solutions to optimize the code and eliminate the N+1 query problem, including any best practices that could be applied. Provide your analysis in a structured format, highlighting key findings and recommendations.
Identify Query Patterns
Examine the following code snippet for repeated database access patterns within loops: [PASTE CODE]. Identify and list any queries that are executed multiple times unnecessarily, along with a brief explanation of how this could impact performance. Additionally, suggest possible optimizations to reduce redundant database calls and improve efficiency. Format your response as a structured report with clear headings for each identified query and its corresponding optimization suggestion.
Review Query Execution
Please review the following function: [PASTE FUNCTION]. Analyze the database queries within this function to determine if they are executed in a loop. Summarize the potential impact of this looping behavior on performance, including any implications for efficiency, response time, and resource utilization. Additionally, suggest any optimizations that could be made to improve query execution and overall function performance.
Analyze Query Load
Please analyze the following code block for potential performance issues related to database load caused by queries within loops: [PASTE CODE]. Identify specific areas where the query load may be excessive and explain the impact this could have on overall application performance. Additionally, suggest optimization strategies to reduce the load and improve efficiency. Your response should be detailed and include examples of how to refactor the code to minimize database calls.
Detect Inefficient Queries
Inspect the following section of code for any inefficient query execution patterns: [PASTE CODE]. Specifically, identify and highlight any instances of the N+1 query problem, explaining why each identified instance is inefficient. Additionally, provide suggestions on how to refactor the code to optimize the queries and improve performance. Your response should be structured in a clear format, detailing each issue and its corresponding solution.
Focus on restructuring the code to batch database queries.
Batch Queries Together
Refactor the following code to batch the queries instead of executing them inside a loop: [PASTE CODE]. Ensure that the new implementation improves performance by reducing the number of database calls. Provide the revised code along with a brief explanation of how the batching process works and any potential benefits it brings to the overall execution. Additionally, include any considerations or caveats that should be kept in mind when implementing this change.
Optimize Query Execution
Please optimize the following loop-based query execution code: [PASTE CODE]. Transform it into a single batch operation to enhance performance. Explain the changes made and how they improve the efficiency of the query execution. Provide the optimized code along with a brief summary of the benefits of using batch operations over loop-based execution.
Consolidate Database Calls
Please consolidate the multiple database calls found in the following code snippet: [PASTE CODE]. Analyze the existing queries and identify opportunities to merge them into a single, efficient query. Provide the revised code along with a brief explanation of the changes made and how they improve performance or readability. Ensure that the new query maintains the same functionality as the original calls.
Improve Query Efficiency
Rewrite the following code to eliminate the N+1 query issue by implementing query batching techniques: [PASTE CODE]. Ensure that the new code improves efficiency by reducing the number of database calls. Explain the changes made and how they contribute to better performance. Provide the final version of the improved code along with a brief summary of the expected benefits.
Streamline Data Retrieval
Please adjust the following code to optimize data retrieval by consolidating it into a single query instead of using multiple calls. The original code is: [PASTE CODE]. Provide the revised version that demonstrates improved efficiency and explain the changes made to achieve this optimization.
Ensure the code no longer suffers from the N+1 query problem.
Confirm Query Reduction
Run the updated code provided below and confirm whether the number of database queries has been reduced. The code to analyze is: [PASTE CODE]. Please provide the query count before executing the updated code and the query count after execution. Additionally, include any observations on the performance improvements or issues encountered during the process.
Validate Performance Improvement
Please validate the performance improvement of the following code: [PASTE CODE]. Execute the code and measure key performance metrics such as execution time, memory usage, and any other relevant benchmarks. Provide a detailed comparison of these metrics against the previous version of the code, highlighting any improvements or regressions. Summarize your findings in a clear format, including specific numbers and any observations that may help in understanding the performance changes.
Check for Remaining Issues
Analyze the updated code provided below for any remaining N+1 query issues. The code is: [PASTE CODE]. Please identify any instances where N+1 query problems persist and provide a detailed explanation of each issue found. Additionally, confirm whether all previously identified issues have been fully resolved and suggest any best practices to prevent such issues in the future.
Ensure Efficient Execution
Please analyze the following database query code: [PASTE CODE]. Evaluate its efficiency in terms of execution time, resource usage, and potential optimization strategies. Provide detailed feedback on any identified issues, suggest improvements, and explain how these changes could enhance performance. Additionally, include best practices for writing efficient queries that could be applied in similar scenarios.
Verify Batch Execution
Please verify the execution of the following queries in batches: [PASTE CODE]. I need you to confirm whether the queries are being executed as intended and provide details on the execution process. Additionally, report any errors or issues encountered during the batch execution and summarize the overall performance of the batch processing. Include any recommendations for optimizing the batch execution if necessary.
Create rules and guidelines to avoid future N+1 query problems.
Create Batching Rule
Draft a new rule for CLAUDE.md that enforces query batching in loops. The rule should specify the conditions under which batching should occur, including any relevant limits on the number of queries per batch and the expected performance improvements. Additionally, include examples of how to implement this rule in code, as well as any potential pitfalls to avoid when applying batching in different scenarios. Ensure the text is clear and concise, suitable for inclusion in the documentation.
Add Comment for Clarity
Please provide a detailed comment to insert in the code that explains the importance of batching queries to prevent N+1 issues. The comment should cover what N+1 issues are, how they can negatively impact performance, and why batching queries is an effective solution. Aim for a clear and concise explanation that can be easily understood by someone reviewing the code, and ensure the comment is formatted appropriately for inclusion in the codebase.
Develop Checklist for Queries
Create a comprehensive checklist to review database query patterns prior to code deployment. The checklist should include items such as: verifying the efficiency of each query, checking for proper indexing, ensuring that queries are optimized to minimize load times, reviewing the use of joins and subqueries for performance impact, and confirming that all queries adhere to security best practices to prevent SQL injection. Additionally, include a section for documenting any potential issues identified during the review and recommended actions to address them.
Establish Naming Convention
Propose a comprehensive naming convention for functions that batch queries in a way that enhances code readability and maintainability. The convention should include guidelines on how to structure function names, such as using prefixes or suffixes to indicate the purpose of the function, and whether to use camelCase, snake_case, or another style. Provide at least five examples of function names that adhere to this convention, explaining the rationale behind each choice and how they contribute to clearer code understanding.
Design Project Guard
Please design a project guard script that automatically detects and warns about potential N+1 query issues in a database application. The script should analyze the database queries executed during runtime and identify any instances where multiple queries are triggered for related data retrieval. Include detailed comments within the script to explain the logic and functionality, and ensure that it provides clear warning messages when N+1 issues are detected. Additionally, outline any configuration options that can be adjusted for different environments or use cases.
Windsurf can analyze your code to detect patterns where database queries are executed inside loops. Use diagnostic prompts to surface these issues and get detailed feedback.
N+1 queries cause excessive database calls, leading to increased latency and reduced application performance. Windsurf helps refactor code to batch queries, mitigating this impact.
Cascade mode allows Windsurf to autonomously edit multiple files, applying changes across your project to fix issues like N+1 queries comprehensively.
Yes, Windsurf can refactor code to batch database queries by following specific prompts that guide it to optimize query execution patterns.
Use Windsurf to create and enforce custom rules in your CLAUDE.md file, ensuring consistent application of best practices like query batching.
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