InterviewHubPRO
Section Overview
Q59

Question 59 of 65

Part 5: ORMs, Databases & Background Workers (56 - 65)

91%
Python & FastAPI•Part 5: ORMs, Databases & Background Workers (56 - 65)

N+1 Query Elimination in SQLAlchemy:

In Simple Words: Fetching 100 posts and iterating their comments triggers 100 individual queries. Fix: Use selectinload() or joinedload() to eager-load relations in a single or secondary batched query.

python
from sqlalchemy.orm import selectinload

# Eager-load all comments using selectinload (eliminates N+1):
stmt = select(Post).options(selectinload(Post.comments))
result = await session.execute(stmt)
posts = result.scalars().all()