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

← All Databases & Transactions questions