# What is an N+1 query?

> An N+1 query is one query for a list plus one more per row. Learn how to spot it, three ways to fix it, and when it is harmless.

Source: https://sqleye.com/blog/what-is-an-n-plus-one-query/ · Published: 2026-10-06 · Last updated: 2026-11-29 · Publisher: CodeROG (https://coderog.com)

An N+1 query pattern is when code runs one query to fetch a list of N rows, then runs one additional query per row to fetch related data, for N+1 queries in total. It is slow because every extra query costs a round trip to the database, and the count grows with the list.

## What does an N+1 look like in SQL?

Say you render a page of blog posts with each post's author name. The first query fetches the posts:

```sql
SELECT id, title, author_id FROM posts ORDER BY id LIMIT 20;
```

The code then loops over the 20 rows and asks for each author separately:

```sql
SELECT id, name FROM authors WHERE id = 7;
SELECT id, name FROM authors WHERE id = 12;
SELECT id, name FROM authors WHERE id = 7;
-- ...and so on, 20 times in total
```

That is 1 query for the posts plus N = 20 for the authors, so 21 round trips to render one page. Nothing is wrong with any single statement. Each one is cheap and correct, which is exactly why the pattern hides well: no individual query is slow, but together they are.

Frameworks and ORMs produce this easily. Code such as `for post in posts: print(post.author.name)` looks like plain property access, but under the hood it may issue a query each time the relation is touched for the first time (lazy loading). How each ORM handles this is a topic of its own, so this post stays framework-agnostic.

## How do I spot an N+1 in a log or query stream?

You are looking for one signature: the same statement, differing only in its literal values, repeated many times in a short burst, usually from one connection. In the example above, the statement `SELECT id, name FROM authors WHERE id = ?` appears 20 times back to back.

Practical ways to find it:

1. Turn on statement logging in your database for a development instance and trigger the page or API call you suspect. Read the log for a repeated statement.
2. Normalise the statements in your head (or with a tool): replace the literals with `?` and see whether the same shape repeats.
3. Count queries per request. Many frameworks have a debug toolbar or a test helper that reports the number of queries a request ran. A count that grows with the size of the list is the tell.
4. Compare. Load the page with 5 rows and with 50 rows. If the query count scales with the rows, you have an N+1.

Note that the burst matters. A statement that is run 20 times over an hour is just a busy query, not an N+1. A statement run 20 times within a few milliseconds by one request is the pattern.

## How do I fix an N+1?

There are three standard fixes. They differ in how much work the database does and how much code changes.

| Fix | Queries issued | Best when | Watch out for |
| --- | --- | --- | --- |
| JOIN | 1 | You need columns from both tables in one result | Duplicated parent rows when the relation is one-to-many |
| Eager loading | 2 | Your ORM supports it; you want objects, not raw rows | Loading related rows you never use |
| Batching with IN | 2 | You have the IDs already and no ORM help | Very long IN lists; mapping rows back to parents |

### Fix 1: JOIN

Ask for everything in one statement:

```sql
SELECT p.id, p.title, a.name AS author_name
FROM posts p
JOIN authors a ON a.id = p.author_id
ORDER BY p.id
LIMIT 20;
```

This is one round trip. For a many-to-one relation like post to author it returns one row per post. For a one-to-many relation (a post and its comments) a JOIN repeats the post columns on every comment row, so you may prefer one of the next two options.

### Fix 2: Eager loading

Most ORMs let you declare up front which relations you will need, and then load them in a fixed number of queries instead of one per row. The usual result is two queries: one for the posts and one for all the authors those posts reference. The exact API differs per framework, so check your ORM's documentation for the term "eager loading" or "preloading".

### Fix 3: Batch the lookups with IN

If you manage queries yourself, collect the IDs first and fetch them in one go:

```sql
SELECT id, name FROM authors WHERE id IN (7, 12, 31, 44);
```

Then match each author to its post in application code, for example with a dictionary keyed by `id`. This is what eager loading does internally. Collect distinct IDs, because 20 posts rarely have 20 different authors.

## When is an N+1 not a problem?

Not every repeated query deserves fixing. It is usually fine to leave it when:

- N is small and bounded. A settings page that loads 3 related rows is not worth a refactor.
- The data is cached. If the per-row lookup is served from an in-process or application cache, the database never sees it.
- The query runs rarely, for example in an admin export or a nightly job where total time is not critical.
- The alternative is worse. A JOIN that multiplies rows, or an eager load that drags in a very large relation you rarely use, can cost more than a few small lookups.

Measure before fixing. A burst of 5 queries that each take a fraction of a millisecond is not the same as a burst of 500 that each wait on the network.

## How does SQLEye help?

> **Note.**
SQLEye is not released yet and there are no downloads. This section describes how it is designed to behave.

SQLEye is a free desktop app that runs local PostgreSQL and MySQL instances and shows each query as it runs. When capture is on for an instance, it normalises every statement into a query shape (literals become `?`, IN lists collapse) and watches for the signature described above.

By default it flags an N+1 when the same shape appears at least 5 times on the same connection within 1000 ms with differing literal values. Both numbers are settings you can change. Repeating the identical statement with identical values is not flagged, and transaction and session statements such as `BEGIN`, `COMMIT` or `SET` are ignored. A flagged burst is collapsed into one expandable row showing how many times it ran. Capture is off by default and only needs to be on while you investigate.

The rule is documented in [N+1 detection](/docs/live-eye/n-plus-one/); see [query shapes](/docs/live-eye/query-shapes/) for how statements are grouped and [capture](/docs/live-eye/capture/) for turning it on per instance.

## Summary

An N+1 is a loop that asks the database a small question many times instead of one larger question once. Find it by looking for one statement shape repeated with different values in a short burst, fix it with a JOIN, eager loading or an IN batch, and skip the fix when N is small or the lookups are cached.
