An N+1 query bug happens when code that looks like a single database fetch actually issues one query to get a list of records, then one additional query per record to get each record’s related data — N+1 total queries instead of one or two. AI code review tools keep approving this pattern because the bug is invisible in a diff: the code is syntactically correct, type-safe, and does exactly what it appears to do on a small, three-row test dataset. The extra queries only pile up once the table holds the thousands of rows a production workload actually has, which is a runtime and data-volume property that a single pull request’s changed lines cannot show.
What the bug actually looks like in code
Take a typical case: fetching a list of orders and then displaying the customer name on each one. In Django ORM, the naive version is Order.objects.all() followed by, inside a template loop, order.customer.name. Each access to order.customer triggers a separate lookup unless the relation was already loaded. In Ruby on Rails, the same shape appears as Order.all followed by order.customer.name inside an each block. In Prisma, it shows up when a resolver fetches a list with prisma.order.findMany() and then, for each order, calls a separate prisma.customer.findUnique() instead of asking Prisma to include the relation in the first query.
None of these snippets contain an error in the traditional sense. They compile, they pass unit tests built on a handful of fixtures, and they return the correct data. A reviewer — human or AI — reading just the changed lines sees a clean loop over a queryset and a property access that any ORM supports. There is nothing in the diff itself that states how many rows the list will hold in production, and that absent context is exactly what turns a harmless-looking loop into a query storm.
Why each ORM’s own fix proves the bug is a loading-strategy problem, not a syntax problem
Every major ORM solves this the same conceptual way: by letting the developer declare, at query time, which related data should be fetched eagerly instead of lazily. Django’s QuerySet API documents select_related() for following single-valued relationships (foreign keys, one-to-one) using a SQL join, and prefetch_related() for multi-valued relationships (reverse foreign keys, many-to-many) using a separate lookup that is joined in Python — both are described in detail in Django’s QuerySet API reference.
Ruby on Rails documents the equivalent idea under eager loading in the Active Record Query Interface guide: calling includes on an association tells Active Record to load the association’s records in a minimal number of queries, rather than issuing one per parent record when the association is touched inside a loop. The guide is explicit that the N+1 pattern is the default behavior of lazy loading, and that includes is the documented way to opt out of it for a specific query.
Prisma frames the same problem from the ORM’s own query-planning side. Its query optimization and performance guide covers the relation-loading strategies Prisma Client can use and the tooling (including the Prisma ORM’s own query-count observability features) to catch a case where a list query is followed by one related-record query per item, rather than Prisma batching those lookups into a single additional query.
The pattern across all three tools is the same: the ORM provides a correct-by-default lazy mode, and a deliberate, separate API call is required to make a specific query path eager. That design means the bug is never a typo or a broken function call — it is the absence of one extra, optional method call that nothing in the type system forces you to add.
Why AI code review tools miss it
AI code review tools — whether a general-purpose assistant reviewing a diff or a dedicated static-analysis product — mostly reason over the text of the change: the lines added, the function being modified, sometimes the file around it. An N+1 bug does not live in that text. It lives in three things a diff rarely contains: the actual row count the list query will return in production, whether the property access inside the loop is already covered by an eager-loading call made somewhere else in the call stack (a service layer two files away, a serializer, a GraphQL resolver), and the database’s query log at runtime.
A reviewer can confirm the first two by reading more of the codebase than the diff shows, and the third only by running the code against a dataset of realistic size and inspecting the query count. Most AI review tools are scoped to the pull request’s diff context for cost and latency reasons, which means they are structurally unlikely to pull in a serializer defined in an unrelated file to check whether it already prevents the problem, and they have no execution environment to observe query counts at all. A tool that only reads static text will see a syntactically valid loop and a property access that any ORM supports, and valid syntax is enough to pass review when the check is confined to “does this code do what it claims.”
This is the same category of blind spot as the one documented in posts about why AI code review misses race conditions — the common thread is that both race conditions and N+1 queries are properties of execution under real conditions (concurrency, or data volume) rather than properties of the text sitting in the diff.
A practical checklist for catching it in manual review
Since the diff alone will not show the problem, reviewing for N+1 queries means asking a short, specific set of questions about any loop that touches a related object:
- Does the loop body access a relation (a foreign key, a reverse relation, an association) on each item? If yes, treat that line as a candidate regardless of how small it looks.
- Was the queryset or query that produced the list built with an explicit eager-loading call —
select_related/prefetch_relatedin Django,includesin Rails, anincludeclause in Prisma’s query — covering exactly the relation being accessed in the loop? Aselect_related('customer')does not cover a later access toorder.items; each relation needs its own coverage. - If the eager-loading call exists somewhere, is it in the same method as the loop, or was it added in a different layer (a base queryset in a manager, a default scope) that a later refactor could silently remove? Eager-loading calls added far from where they are consumed are the most common place this regresses.
- Has anyone actually looked at the query log or a query-count assertion for this code path against a dataset sized closer to production than a three-row fixture? A unit test with three orders will not reveal a problem that only costs real time at three thousand.
- If the code is behind a paginated list endpoint, does the page size bound how bad an unfixed N+1 can get, or can an API consumer request an arbitrarily large page and multiply the problem?
Running through this list takes a few minutes per loop and catches the overwhelming majority of cases, because the fix is almost always the same shape: find the relation being accessed inside a loop, and confirm there is a corresponding eager-loading call that covers that exact relation, made as close as possible to the query that produces the loop’s input.
Where automated tooling does help
None of this means automated tools are useless here — they are just the wrong layer if scoped only to diff text. Application performance monitoring tools that trace real requests can flag a single request that issued dozens of near-identical queries, because they observe the actual query log rather than the source code. That observability-based detection, run against staging or production traffic, is a better fit for this bug than a text-based review step, because it checks the one thing that actually proves the bug exists: the number of queries a real request generated.
The practical takeaway is to treat AI-assisted code review as a check for logic errors in the diff, and treat query-count regressions as a separate, runtime-based check — either a lightweight assertion in a test that counts queries against a realistically sized fixture, or a monitoring alert on query count per request in staging. Relying on either check alone leaves exactly the gap this bug lives in.
Writing a Query-Count Test That Actually Catches a Regression
For related reading on this blog, see The Off-By-One Mistake That Breaks AI Code Review on Long Diffs, Reviewing AI-Generated Pull Requests: A Commented Checklist for Human Reviewers, Why AI Code Review Suggestions Miss Race Conditions (And What to Check Manually), Reviewing an MCP Server’s Permissions Before You Connect It to Claude Code, and A Commented Checklist for Reviewing an AI-Generated GitHub Actions Workflow Before It Runs on Your Main Branch.
The most durable fix available to a team, beyond manual review vigilance, is a small automated test that asserts on query count directly rather than relying on a human noticing a missing eager-load call during review. Django’s test framework ships assertNumQueries as a context manager specifically for this, documented in Django’s testing tools reference, which fails the test if the wrapped code executes more or fewer queries than the number asserted. Rails projects commonly reach for the community bullet gem, which hooks into Active Record’s query log during development and test runs and raises a notification the moment it detects an N+1 pattern, rather than waiting for a human to spot it in a code review. Writing one such test per list-plus-relation endpoint, seeded with enough fixture rows that an N+1 would actually show a visible difference (ten or more related rows, not two), turns this from a judgment call during review into a check that fails the build automatically if a future change reintroduces the pattern — which matters because the checklist above still depends on a reviewer remembering to apply it every time, and a failing test doesn’t.
Featured image: Pavel Fric, CC BY-SA 4.0, via Wikimedia Commons.



