What are N+1, eager loading and lazy loading?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn What are N+1, eager loading and lazy loading?
Definition:
N+1 is a data-access pattern where fetching N parent records leads to roughly N more queries for related records. Eager loading fetches configured relations up front, while lazy loading waits until the relation is accessed. Both loading styles can waste work if they do not match the endpoint's real needs.
Key points:
-
N+1 means one list query followed by a query for each row.
-
Eager loading fetches configured relations automatically; lazy loading fetches on access.
-
Use measured joins or batch queries, and select only needed fields.
-
A giant join can multiply rows; batching can sometimes be clearer and cheaper than loading every relation at once.
Interview point:
- Count queries and returned rows, not just the number of lines in the repository call.
Adapted from 03_NESTJS.md · “What are N+1, eager loading and lazy loading?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.