Database N+1 Query Problem Killing Performance
Your application loads slowly because the database receives hundreds of queries for what should be done in a few. The N+1 query problem: fetching a list of items, then one query per item to fetch related data.
N+1 queries happen when data fetching doesn't use joins or batch queries, instead fetching parent items then querying for each child.
Error Messages You Might See
Common Causes
- In loop: fetching related data one item at a time instead of using JOIN or batch query
- Not using Prisma select/include, loading all fields unnecessarily
- ORM not eager-loading related entities by default
- Mapping/transforming data in application layer instead of database
- No query analysis or monitoring to detect N+1 patterns
How to Fix It
Use database joins: In SQL, use JOIN to fetch related data in single query. In Prisma, use include(): await prisma.user.findMany({ include: { posts: true } })
Batch queries: If joins not possible, fetch related data in batch: const postsMap = await prisma.post.findMany({ where: { userId: { in: userIds } } })
Enable query logging: Add logging to see duplicate queries. Prisma: set log level, check for repeated queries.
Use select: Don't fetch unnecessary fields: select: { id: true, name: true } instead of full object.
Real developers can help you.
You don't need to be technical. Just describe what's wrong and a verified developer will handle the rest.
Get HelpFrequently Asked Questions
How do I detect N+1 queries?
Enable Prisma query logging or use Vercel Analytics. Look for same query repeated multiple times in logs.
What's the difference between select and include?
Select: specify exact fields to fetch. Include: fetch related entities (relations). Use select for partial data, include for relations.
Can I fix N+1 without rewriting queries?
Add caching layer. Cache user objects after first fetch. Reduces query count even if queries aren't optimized.