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
Cursor generates database access code that runs queries inside loops, leading to inefficient N+1 query problems. This causes significant performance degradation and increased load times. These prompts help developers identify and batch queries, improving efficiency and performance. 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 where queries are being executed inside loops.
Identify Query Locations
Please analyze my codebase and identify all the locations where database queries are executed. For each instance, provide the corresponding file names and line numbers. Additionally, include a brief description of the type of query being executed at each location, such as SELECT, INSERT, UPDATE, or DELETE. Format the results in a clear list for easy reference.
Check Loop Usage
Identify all loops in my project that contain database queries. For each loop, provide the name of the loop, the specific query being executed, and the context in which the loop is used. Additionally, analyze the potential performance implications of these queries within the loops and suggest any optimizations that could be made to improve efficiency. Format the results in a clear, structured list for easy reference.
Analyze Query Patterns
Please analyze the following code for patterns of repeated queries that may lead to N+1 query issues. Focus on identifying any loops that execute database queries multiple times, and provide a detailed explanation of how these patterns can be optimized. Additionally, suggest best practices for reducing the number of queries and improving overall performance. Present your findings in a structured format, including specific examples from the code and recommended changes.
Review Query Performance
Analyze the performance impact of queries executed within loops in my application. Identify and summarize the queries that are consuming the most resources, including their execution time and frequency of calls. Provide recommendations on how to optimize these queries to improve overall performance. Format the findings in a clear report that highlights the top three most resource-intensive queries and actionable steps for optimization.
Locate Inefficient Code
Identify sections of code in my project where queries could be batched instead of executed individually. Provide a detailed analysis of the current implementation and highlight the specific areas that are causing inefficiencies. Suggest concrete improvements for batching queries, including examples of how to implement these changes effectively. Additionally, explain the potential performance benefits of these optimizations in terms of execution time and resource usage.
Focus on modifying code to batch queries effectively.
Refactor for Batching
Refactor the following code to implement batching for database queries instead of executing them within loops. Ensure that the new implementation minimizes the number of database calls by grouping multiple queries together. Provide the modified code with clear comments explaining the changes made, and include any necessary adjustments to maintain functionality. Additionally, outline the benefits of using batching in this context, such as improved performance and reduced load on the database.
Optimize Query Logic
Please analyze the logic of my current database queries and provide an optimized version that reduces the number of calls made to the database. Include specific changes you recommend, along with the reasoning behind each optimization. Present the optimized code in a clear format, highlighting the differences from the original queries and explaining how these changes improve performance and efficiency.
Implement Bulk Operations
Please help me implement bulk operations for database interactions in my application. I need the updated code that demonstrates how to perform these operations efficiently. Include explanations for each part of the code to clarify how the bulk operations improve performance and reduce the number of database calls. Additionally, provide examples of scenarios where bulk operations would be beneficial and any potential limitations to consider.
Use Efficient Data Structures
Suggest efficient data structures that can be used for batching queries in a programming context. Explain why each data structure is suitable for this purpose and how it improves performance. Provide examples of how to implement these data structures in code, including before and after snippets to illustrate the changes made. Additionally, discuss any potential trade-offs or considerations when using these data structures in a real-world application.
Simplify Query Execution
Consolidate the execution of multiple queries into a single, simplified query. Please provide the revised code that achieves this consolidation, ensuring that it maintains the same functionality as the original queries. Additionally, explain the changes made, detailing how the new approach improves efficiency and readability. Include any relevant considerations for performance and potential impacts on data integrity.
Ensure that the changes have resolved the N+1 query problem.
Run Performance Tests
Please run performance tests on the modified code to verify that the N+1 query issue has been resolved. Provide a detailed report of the test results, including metrics such as response time, memory usage, and any other relevant performance indicators. Additionally, compare these results to the previous performance metrics before the code modification. Summarize any improvements or regressions observed and include recommendations for further optimization if necessary.
Confirm Query Reduction
Please confirm whether the number of database queries has been reduced. I would like a detailed comparison of the query counts before and after the reduction. Include specific numbers for each stage, and analyze the impact this reduction has on performance and efficiency. Additionally, provide any recommendations for further optimization based on your findings.
Check Code Efficiency
Evaluate the overall efficiency of the following code after modifications: [INSERT CODE HERE]. Analyze its performance by providing key metrics such as execution time, memory usage, and any potential bottlenecks. Additionally, offer feedback on specific improvements made during the modifications and suggest further optimizations if necessary. Present your findings in a structured report format, highlighting both strengths and areas for enhancement.
Validate Batch Processing
Please validate the batch processing of queries and confirm that it is functioning correctly. Provide a detailed report that includes evidence of successful batch operations, such as timestamps, the number of queries processed, and any error messages encountered during the process. Additionally, summarize the overall performance metrics and any recommendations for improving efficiency in batch processing. Format the results in a clear and organized manner, ideally in a table or bullet points for easy reference.
Review Execution Logs
Please review the execution logs for the new batch processing logic. Identify any errors or anomalies that may have occurred during the execution. Summarize your findings in a clear report, highlighting any specific issues, their frequency, and potential impacts on the system. Additionally, provide recommendations for resolving any identified errors and improving the batch processing logic moving forward.
Create safeguards to avoid future N+1 query problems.
Draft CLAUDE.md Rule
Draft a new rule for my CLAUDE.md that addresses and prevents N+1 query issues based on the recent fixes I have implemented. The rule should clearly outline the definition of N+1 queries, the potential impact they can have on performance, and best practices for avoiding them in future development. Include specific examples of how to identify N+1 queries in the code and suggest strategies for optimizing database queries to enhance efficiency. Format the rule in a clear and concise manner, suitable for inclusion in the documentation.
Add Code Comments
Please provide the code that demonstrates batching queries, and insert comments throughout the code to explain the importance of this practice. The comments should cover the benefits of batching, such as improved performance, reduced server load, and enhanced readability. Ensure that the comments are clear and concise, making it easy for someone unfamiliar with the code to understand the rationale behind batching queries. Format the output with the original code followed by the updated version with comments included.
Create Session Checklist
Please create a detailed checklist to review before starting a session that ensures queries are properly batched. The checklist should include items such as verifying the data sources, confirming the query parameters, checking for any dependencies, and ensuring that the batching logic is correctly implemented. Format the checklist in bullet points for easy readability, and provide a brief explanation for each item to clarify its importance in the session preparation process.
Establish Naming Conventions
Help me establish clear naming conventions for functions that handle database operations, specifically to indicate when batching is being used. I would like to see a structured format that includes prefixes or suffixes that can be consistently applied, along with examples of function names that follow these conventions. Additionally, please explain the rationale behind each naming choice and how it enhances code readability and maintainability. Aim for at least five examples and a brief summary of best practices for naming conventions in this context.
Develop Project Guard
Create a project guard that monitors code for queries executed within loops and sends alerts when such occurrences are detected. Include the complete code for the guard, ensuring it is compatible with [PROGRAMMING LANGUAGE] and can be easily integrated into existing projects. Additionally, provide detailed setup instructions that cover installation, configuration options, and examples of how to test the guard's functionality. Make sure to explain any dependencies required for the guard to operate effectively.
Cursor may generate N+1 queries if the code logic involves executing queries inside loops without batching. It lacks context awareness over long sessions, leading to inefficient query patterns.
Use the .cursorrules file to define project-specific instructions that enforce query batching. Regularly update these rules to guide Cursor's code generation.
N+1 queries significantly degrade performance by increasing database load and response times. They result from executing individual queries in loops instead of batching them.
Cursor's context loss over long sessions can lead to repeated query generation patterns, as it may not remember previous optimizations or batching instructions.
Cursor can suggest batching strategies if guided by clear rules in the .cursorrules file. Developers should ensure these rules are comprehensive and up-to-date.
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
Running database queries inside a loop can lead to performance issues known as the N+1 query problem.
See prompts