In plain words

Django's own documentation shows the problem in a dozen lines. A Pizza model has a many-to-many toppings field, and its __str__ method joins the topping names with self.toppings.all(). Print every pizza and nothing in the loop looks like a database call. Django still runs one query for the pizzas and then, in the docs' words, "a query on the Toppings table for every item in the Pizza QuerySet".

The name is that count: one query for the list, plus one per row. Many ORMs load related objects lazily, meaning a relationship attribute sends a SELECT the first time code reads it. Read it inside a loop over N objects and you get N+1 queries. EF Core's docs point out that each of those queries runs "in its own roundtrip" to the database.

An ORM is not required. Hibernate's guide says the problem "even affects typical handwritten JDBC code behind DAOs". Code without any data library does it too: DataLoader's README describes a naive application that "may have issued four round-trips to a backend" where batching needs at most two. No library can guess what a loop will touch next, which is why Hibernate puts the fix on you: "only you know ahead of time what data you're going to need in a given unit of work."

How it works

  1. One query loads the list of N parent rows.
  2. Code loops over the results and reads a relationship that was not loaded with them.
  3. Each read sends its own query filtered by that row's key: pizza_id = 1, then pizza_id = 2, and so on.
  4. The loop ends after N+1 queries, where a JOIN or one batched query would have returned the same rows.

We ran the docs' models unchanged on Django 6.1.3 (Python 3.13.18, in-memory SQLite 3.53.1) with 100 pizzas of two toppings each, and counted queries with Django's CaptureQueriesContext. The last two lines are ours:

from django.db import models

class Topping(models.Model):
    name = models.CharField(max_length=30)

class Pizza(models.Model):
    name = models.CharField(max_length=50)
    toppings = models.ManyToManyField(Topping)

    def __str__(self):
        return "%s (%s)" % (
            self.name,
            ", ".join(topping.name for topping in self.toppings.all()),
        )

[str(p) for p in Pizza.objects.all()]                         # 101 queries
[str(p) for p in Pizza.objects.prefetch_related("toppings")]  # 2 queries

The plain loop sent 101 queries, each ending in WHERE "pizzas_pizza_toppings"."pizza_id" = 1 with a different id. With prefetch_related, Django sent two: the pizza query and one topping query ending in "pizza_id" IN (1, 2, 3, 4, 5, ..., then matched toppings to pizzas in Python. The printed output was identical.

Three ways to fix it

StrategyWhat reaches the databaseNames in common libraries
Join fetchOne query with a JOIN that returns parents and related rows togetherHibernate join fetch or an EntityGraph, Rails eager_load, SQLAlchemy joinedload(), Django select_related(), EF Core Include, Prisma relationLoadStrategy: "join"
Second query by keyThe parent query, then one query for all related rows with WHERE key IN (...)Django prefetch_related(), Rails preload, SQLAlchemy selectinload(), Prisma include, EF Core split queries, Hibernate subselect fetching (keys re-queried as a subselect) or batch fetching (one query per batch of keys)
Batch in application codeLookups made in the same event-loop tick merged into one fetchDataLoader, and Prisma's automatic batching of findUnique()

Rails' includes picks between preload and eager_load for you, and its guide recommends starting there. Elsewhere the docs disagree on a default. Hibernate says "you should almost always use outer join fetching" and that batch fetching "might mitigate" N+1 but "won't solve" it. SQLAlchemy calls selectinload() "generally the best loading strategy" for one-to-many and many-to-many collections and keeps joinedload() for many-to-one.

Both sides document the same limit, which settles most cases: join a to-one relationship, and give a collection its own query once a join would multiply rows. Hibernate makes that exception for two collections fetched together. Django builds it in by allowing select_related only on foreign keys and one-to-one fields; on our run, Pizza.objects.select_related("toppings") failed with FieldError: Invalid field name(s) given in select_related: 'toppings'. Choices are: (none). SQLAlchemy enforces a smaller version: a joinedload() on a collection raised The unique() method must be invoked on this Result until we added .unique().

Catching N+1 before it ships

Hibernate's first advice is to log the SQL, because even when everything works "there might be a lurking N+1 selects monster". In the log it shows up as the same statement repeated with a different key each time.

Because the fix is a decision per query, make a missed one fail loudly. SQLAlchemy's raiseload() replaces lazy loading "with an informative error"; on SQLAlchemy 2.1.9, reading the attribute raised sqlalchemy.exc.InvalidRequestError: 'User.addresses' is not available due to lazy='raise'. Rails' strict_loading raises ActiveRecord::StrictLoadingViolationError, and Django's assertNumQueries pins a function's query count in a test.

Why it matters

Hibernate's guide calls N+1 selects "the most common cause of poorly-performing data access code in Java programs". It survives code review because no single query is slow; EF Core's sample log shows one of the per-blog queries as Executed DbCommand (1ms). The cost is the number of round trips, which grows with the number of rows the first query returns.

Making every relationship eager does not fix it. Hibernate calls eager mapping by default "a terrible idea, resulting in simple session operations that fetch almost the entire database", and calls JPA's eager default for @ManyToOne "a very unfortunate misfeature". The documented approach is lazy mappings plus an explicit fetch in each query that needs the related data.

Outside ORMs, DataLoader does the batching. It collects every load() call made in "a single tick of the event loop" and hands all the keys to one batch function. We tried it on Bun 1.4.0 with dataloader 2.2.3: ten load() calls for posts by four authors became a single batch call with keys [1,2,3,4]. Prisma batches findUnique() calls in the same tick automatically. Its query API is compared with Drizzle's in Drizzle vs Prisma.

Common confusions

TermWhat it isHow it differs from N+1
Lazy loadingLoading a relationship the first time code reads it. SQLAlchemy relationships do this by default.The mechanism, not the problem. It becomes N+1 only when the read happens once per row in a loop.
Eager loadingLoading relationships along with the parent query, by JOIN or by a second query.The fix. Mapping every relationship as eager by default is a separate problem.
Cartesian explosion (cartesian product)A JOIN across a one-to-many relationship repeats the parent's columns on every child row. EF Core's name for it.The opposite failure: too few queries returning too many rows. EF Core's answer, split queries, is the second-query strategy.
Slow queryOne statement that takes too long, most often because it cannot use an index.N+1 is many fast statements. A slow query is fixed with indexes or query planner work; N+1 is fixed by sending fewer queries.