Skip to content
Minute Campus.

Almost rightLesson 071 min

Correct, and far slower than it should be

The code fetches a list of orders with one query, then sends another query for each order to look up the customer's name. With a hundred orders that is a hundred and one trips to the database. It feels instant on test data and crawls on a hundred thousand orders. This is the N plus one problem. A join returns everything in a single query.

Remember

A database query inside a loop is a warning sign, so count your queries.

Transcript

The lesson, word for word.

Read it at your own pace, or search the page for a term.

This code is correct, and far slower than it should be. Three seconds: why? It prints a list of orders, each with the customer's name. First, one query fetches all the orders. Then it loops. For every order, it sends another query to look up that customer's name. With a hundred orders, that is a hundred and one trips to the database. The result is right, and with ten rows of test data it feels instant. With a hundred thousand orders, the page crawls. This is called the N plus one problem: one query for the list, then one more for each of the N items. The fix is to ask once. A join tells the database to match orders to customers, and send everything back in a single query. Same result, one trip. The rule: a database query inside a loop is a warning sign. Count your queries, not just your results.

Questions? Comment on the lesson on YouTube

New lessons every day.

Follow Minute Campus where you already scroll.