Fix N+1 Database Query Patterns in ORM Code

This prompt identifies N+1 query issues in your code, provides the optimized eager-loading syntax, and calculates the reduction in database round-trips.

Prompt

Prompt
Act as a Senior Backend Engineer. Your task is to audit code for N+1 query patterns. Wait for me to paste my ORM code snippet and the associated model relationships. Once I provide the code, follow these rules: 1. Identify the exact line causing the N+1 issue. 2. Provide the corrected code using eager loading or batching syntax for my specific framework. 3. Calculate the number of queries executed in the current version versus the optimized version, assuming a list of 50 items. 4. Explain why the change improves performance without using jargon. Output format: ## Analysis of N+1 Pattern. ## Optimized Code Implementation. ## Query Count Comparison (Before vs After). ## Performance Impact Summary. This analysis is for architectural guidance and does not replace load testing in your staging environment.

Example output

Example for: a Django view fetching 50 user profiles with associated profile images. ## Analysis of N+1 Pattern The issue exists in the loop where you call user.profile_image for each user object. Because the profile image relationship is not pre-loaded, Django executes a separate SELECT query for every single user in the loop. ## Optimized Code Implementation Use select_related or prefetch_related to fetch data in one trip. users = User.objects.select_related('profile_image').all() for user in users: print(user.profile_image.url) ## Query Count Comparison (Before vs After) Before: 51 queries (1 for the user list + 50 for individual images). After: 1 query (1 join query fetching all data at once). ## Performance Impact Summary By fetching all profile images in a single join, you eliminate 50 redundant round-trips to the database. This significantly reduces the time spent waiting for network latency and database overhead, resulting in a faster response time for the client.

Written by AI from this prompt. Your results will vary.

Tips and common edits

Why this works

  • Forces the model to explicitly calculate query counts to prove the benefit.
  • Requires specific framework-based syntax for immediate application.
  • Includes a clear disclaimer about the need for actual load testing.

Use this prompt when you notice high latency in API endpoints that fetch related data. Paste your controller or service layer code along with the model definitions. Supported in ChatGPT, Claude, and Gemini.

Common edits

  • Add your specific database engine if you need dialect-specific optimizations.
  • Request the output as a Pull Request description if you are documenting the change for a team.

Make it repeatable

Keep using this prompt without pasting it in every time.

Keep exploring

More in Coding