Backend development

Stage 2 · Lesson 10 of 10

The N+1 query problem

Relational databases and SQL

An hides the SQL from you, and the classic cost is the N+1 problem. You load 50 orders with one query. Then you fetch each order's customer inside a loop.

You have now run 51 queries where one or two would do. At 5 ms each, that is a quarter of a second of waiting. In , fetch the related data up front with include or select.

In , use its relational queries with the with option, or write a . In resolvers, a DataLoader collects the per-item lookups into one batch. Turn on query logging in development, such as Prisma's log option, and count the queries per request.

Common traponly testing with three rows, where four queries feel instant.

A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

Practise

Also worth your time

Mark this stage as not done?