Glossary

N+1 Problem

The N+1 problem is an anti-pattern where displaying N records triggers N+1 SQL queries: one to fetch the list, and one per related record. With 100 records — 101 queries; with 1000 — 1001.

How it occurs

An ORM loads a list of objects. Then in a loop, each object accesses a related one — and the ORM silently fires a separate SELECT. Each access looks harmless, but together they kill performance.

Fix: Eager Loading

Instead of separate queries in a loop — one additional query with WHERE id IN (...) for all related records at once. Result: always 2 queries regardless of record count. In most ORMs this is controlled by methods like include, with, joins, or preload.

Diagnosis

Enable SQL query logging and watch for identical SELECTs repeating dozens of times. A query count proportional to the number of rows on the page is a sure sign of N+1.