N+1 query problem
Also called: N+1 problem
Running one query for a list and then one more query per item to load its related data.
Definition
The N+1 problem appears when code loads N records and then accesses an association of each, triggering a separate query per record. It is fast with test data and slow in production, where N is large. Fixes include fetch joins or entity graphs, batch fetching, and selecting exactly the needed columns into DTOs. Counting SQL statements per request in tests catches it early.
In practice
An endpoint that lists 500 authors with their book counts runs 501 queries instead of one grouped query.
Learn it in context
Lessons that use this term.