Skip to content
Ameen Abozaid
Planned lessonJNR-032-L01

The N+1 problem

  • Lesson 1 of 7
  • Junior
On This Lesson 4 topics

This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.

In this lesson

recognize N+1 in logs and tests.

Planned topics

  • N+1: one query loads N parents, then one more query per parent loads its children (or relation).
  • 100 orders become 1 + 100 = 101 queries.
  • It hides in lazy relations touched in a loop, or in mapping code that reads order.getCustomer().getName().
  • Detect it in the SQL log (repeated similar selects) or with a query counter in tests.
  • It is fast on a developer machine with 5 rows and slow in production.
Draft outline details

Demonstration

java
List<Order> orders = orderRepository.findAll();          // 1 query
for (Order o : orders) {
    System.out.println(o.getLines().size());             // +1 query per order
}

Check your understanding

How many queries for 100 orders with N+1?

Show answer

101.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.