N+1 Query Problem
PronunciationEN plus WUN
Definition
A performance bug: one query loads a list of N items, then the code runs one extra query for each item, so you get N+1 queries.
Where you hear it
ORM performance reviews and slow-page investigations.
Examples
The page runs 101 queries because of an N+1 problem.
Use
select_relatedto load the related data in one query.Loading each author inside a loop turned the list page into an N+1 problem.
Common mistake
Testing only with 5 rows. The problem appears only with thousands of rows in production.
Don't confuse with
A slow database index and the N+1 problem are different. An index makes one query faster, while N+1 runs many small queries, one per row, that an index cannot fix. The usual fix is to load the related rows in one query, for example with eager loading.
Say it at work
- In a meeting or chat
We need to fix this N+1 query issue on the dashboard before we release it to production.
- In an email or ticket
This pull request introduces an N+1 query problem when fetching user profiles, please use eager loading instead.