Databases & Transactions interview question · Most asked
What is the N+1 query problem and how do you fix it?
Summary
N+1 happens when code loads a list (1 query) and then lazily queries a relation for each item (N queries), multiplying round trips. Fix it with eager loading (JOIN or batched IN queries), DataLoader-style batching, or selecting needed data in one query.
Longer Answer
Every ORM has tools: selectinload/joinedload (SQLAlchemy), with() (Eloquent), JOIN FETCH/@EntityGraph (JPA), include (Prisma), prefetch_related/select_related (Django). Detect it with query logging, APM traces or test assertions on query counts.
Key Points
- 1 + N round trips
- Eager or batched loading
- DataLoader for GraphQL
- Detect via logs/traces/tests
More most-asked Databases & Transactions questions
- What does ACID mean?
- Explain transaction isolation levels and the anomalies they prevent.
- How do database indexes work and when do they help or hurt?
- How do you choose between SQL and NoSQL databases?
- What is connection pooling and how do you size a pool?
- How do you run schema migrations without downtime?
- How do you keep data consistent across services without distributed transactions?