avoid-n-1-queries
Installation
SKILL.md
Summary
Do not issue a database query inside a loop that iterates over the results of another query. Use Eager Loading (fetching relations in the main query) or Batching (fetching all relations in one go).
Rationale
- Performance: Executing 101 queries (1 main + 100 children) is significantly slower than executing 1 or 2 queries due to network latency and database overhead.
- Scalability: An N+1 problem might not be noticeable with small datasets but causes massive slowdowns as data grows.
Guidance
- Identify Loops: Look for loops where a DB call happens in each iteration.
- JOIN: Use
JOINto fetch related data in a single query. - WHERE IN: Keep IDs and fetch all related records using
WHERE id IN (...). - ORMs: Use your ORM's eager loading features (e.g.,
Preloadin Gorm,Includein Prisma).