Skip to content
EduVerse

N+1 Problem

Explained

Concept

Also known as: N+1 Query

A common performance problem where one query triggers N extra queries, one per row.

N+1 Problem, explained

Written by EduVerse

What it is

The N+1 problem is a common performance trap in database code. You run one query to fetch a list, and then your code fires one extra query for every row in that list to load related data. It often hides inside an ORM, where lazy loading makes those extra queries invisible.

Why teams use it

Every query costs a round trip to the database. With ten rows nobody notices, but with thousands the page slows to a crawl and the database works far harder than it should. The usual fix is a join or eager loading, so the related data arrives in one or two queries.

An example from work

A page listing 50 orders feels slow, so you switch on SQL logging. The console shows one SELECT on the orders table, followed by 50 nearly identical SELECT statements on customers, one per order. Telling the ORM to load the customers together with the orders brings it back to one or two queries.

Our own explanation, not a quote from the book.

Where it fits

Database optimisation, working with ORMs

Coverage in the book

Explained

Explained and compared with alternatives, so you know where and why it’s used.

Appears in