Skip to content
mentoor

Topic 1 of 5 · 5 min read

Spotting N+1 database queries

Goal: Find an N+1 query pattern in AI-written data access code and choose the batched or eager-loaded fix.

An N+1 query is one query to fetch a list, followed by one more query for every row in that list; spot it by looking for a database call inside a loop. AI assistants write this pattern all the time, because it is the most direct way to turn "show each order with its customer" into code.

Check yourself · 1 of 3

What is the clearest sign of an N+1 query problem in AI-written code?

Choose one answer

Why it matters

With 5 rows in a test database you never notice. With 2,000 rows you run 2,001 queries. Each query pays a network round trip, so a page that took 20 ms now takes seconds, and the database server is busy with thousands of tiny requests. The code is correct. It is just slow, so tests stay green.

ORMs make it worse because the extra query is invisible. Writing order.customer.name looks like reading a field, but it may trigger a lazy load. Claude, ChatGPT, Copilot and Cursor all produce this, since the code mirrors how a person would describe the task.

How to spot it

  1. Look for any database call, ORM relation access or repository method inside a for, map or comprehension.
  2. Ask: how many queries run if the list has 1,000 rows? If the answer is 1,001, it is N+1.
  3. Turn on query logging or a query counter in a test and assert the count. Django's assertNumQueries is one example.

How to fix it

  • Eager loading. Tell the ORM to load the relation with the list: select_related or prefetch_related in Django, include in Prisma, joinedload in SQLAlchemy.
  • A join. One query that returns rows from both tables.
  • Batching. Collect the ids, run one WHERE id IN (...) query, then match results in memory.

Before and after

# Weak: 1 query for orders + 1 per order for the customer
for order in Order.objects.filter(status="open"):
    print(order.customer.name)

# Fixed: 1 query with a join
for order in Order.objects.filter(status="open").select_related("customer"):
    print(order.customer.name)

What goes wrong

  • Over-fetching. Eager loading a large relation you never use makes things slower. Load only what the code reads.
  • Giant IN lists. Batching 100,000 ids in one query can hit database limits. Chunk them.
  • Fixing the wrong layer. Wrapping the loop in a cache hides the problem and adds stale data.

Examples

Lazy load in a template loop

An agent builds an invoices page. The view loads 500 invoices and the template prints invoice.client.company for each one. The log shows 501 queries. Adding select_related("client") to the query brings it to 1, and a test with assertNumQueries(1) locks it in.

Batching without an ORM

// Weak: one query per user id
const names = [];
for (const id of ids) {
  const u = await db.query("SELECT name FROM users WHERE id = $1", [id]);
  names.push(u.rows[0].name);
}

// Better: one query for all ids
const res = await db.query("SELECT id, name FROM users WHERE id = ANY($1)", [ids]);

The second version makes one round trip. Remember that the rows come back in no guaranteed order, so map them by id.

Key points

  • A database call, relation access or repository call inside a loop is the signature of an N+1 pattern.
  • Ask how many queries run for 1,000 rows; the answer should not grow with the row count.
  • ORM lazy loading hides the extra query behind what looks like a plain field read.
  • Fix with eager loading, a join or a batched IN query, and load only the relations the code uses.
  • Assert the query count in a test so the regression cannot return.

Common mistakes

  • Reviewing only the loop body and missing that a property access triggers a query.
  • Testing with 3 rows and declaring the code fast.
  • Adding a cache around the loop instead of removing the per-row query.
  • Eager loading every relation by default, which fetches data nobody reads.

Check yourself · 2 of 3

A page lists 1,000 orders and prints each order's customer name through a lazy-loaded relation. Roughly how many queries run?

Choose one answer

Check yourself · 3 of 3

Which change fixes an N+1 pattern without loading unneeded data?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic