N+1 problem: 1 query lấy N records, rồi N queries nữa để lấy related data.
Giải quyết bằng eager loading.
python
# N+1 problem — 1 + N queries
users = await db.execute(select(User))
for user in users.scalars():
posts = await db.execute( # 1 query mỗi user!
select(Post).where(Post.user_id == user.id)
)
# Fix: selectinload — 2 queries total
from sqlalchemy.orm import selectinload
result = await db.execute(
select(User).options(selectinload(User.posts))
)
# 1 query lấy tất cả users + 1 query lấy posts cho tất cả user_ids
# joinedload — 1 query với JOIN (tốt khi result set nhỏ)
from sqlalchemy.orm import joinedload