The N+1 Query Problem: Why Your Database Runs 500 Queries Instead of 5

Overview

Have you ever profiled a slow page and found that the application is making hundreds of database queries for a page that should only need five?

The code looks fine and there are no bugs. The right data is showing. But the database is being asked the same question over and over, with just one value changing each time.

This is called the N+1 query problem. In this article, you'll learn what it is, why it's so easy to miss, and three ways to fix it.

What Is the N+1 Query Problem?

Let's say you have a page that lists recent orders, and shows the customer name for each one.

The application first gets the orders:

1SELECT order_id, customer_id, order_date, order_total
2FROM orders
3WHERE order_date >= '2026-11-01';

Then, for each order, it looks up the customer:

 1SELECT customer_name
 2FROM customer
 3WHERE customer_id = 1042;
 4
 5SELECT customer_name
 6FROM customer
 7WHERE customer_id = 877;
 8
 9SELECT customer_name
10FROM customer
11WHERE customer_id = 3310;
12
13-- ...and so on, once for every order

That's one query to get the list (the "1"), plus one query for each row in the list (the "N"). If the first query returns 500 orders, the page runs 501 queries.

Each of those queries is fast on its own. The customer lookup uses the primary key, so it probably takes a millisecond or less. But every query has overhead: a round trip over the network, parsing, and returning the results. Do that 500 times on every page load, and it adds up quickly.

Why It's So Easy to Miss

The N+1 problem rarely shows up in development.

In dev, your orders table might have 20 rows. The page makes 21 queries and loads instantly. Nobody notices.

In production, the same page might return 500 or 5,000 rows. Now it makes thousands of queries on every request, and the page is slow.

It's also easy to create without writing any SQL yourself. ORMs like Hibernate, Entity Framework, Django and ActiveRecord load related data lazily by default. Code like this looks completely harmless:

1orders = Order.objects.filter(order_date__gte="2026-11-01")
2
3for order in orders:
4    print(order.customer.customer_name)

But each time the loop accesses order.customer, the ORM sends another query to the database.

How to Spot It

The giveaway is the same query running many times in a row, with only one value changing.

A few ways to find it:

  • Turn on SQL logging in your ORM or framework in development, and look for repeated queries.
  • Use a profiling tool for your framework, such as Django Debug Toolbar, MiniProfiler, or your APM tool, which will show the query count per request.
  • Check your database's query statistics for a simple query with a very high execution count.

Fix 1: Use a JOIN

The simplest fix is to get everything in one query, using a JOIN:

1SELECT o.order_id, o.order_date, o.order_total, c.customer_name
2FROM orders o
3INNER JOIN customer c ON o.customer_id = c.customer_id
4WHERE o.order_date >= '2026-11-01';

This goes from 501 queries to 1. The database is very good at joining tables, so this one query is usually much faster than the 500 small ones.

Sometimes a JOIN isn't a good fit. For example, if each order has many order lines, joining them would repeat the order columns on every line.

In that case, you can run two queries instead of N+1. First, get the orders. Then, get all of the related rows in a single query using IN:

1SELECT order_id, product_id, quantity, line_total
2FROM order_line
3WHERE order_id IN (5001, 5002, 5003, 5004, 5005);

Your application then matches the lines to their orders in memory.

This takes you from N+1 queries to 2, no matter how many orders there are. If the list of IDs is very large, you can split it into batches of a few hundred or a few thousand.

Fix 3: Tell Your ORM to Load Eagerly

If you're using an ORM, you don't need to write the SQL yourself. Most ORMs have a way to load related data up front, which is called eager loading.

Here's what it looks like in a few popular ORMs:

ORM Eager loading
Django select_related("customer") or prefetch_related("lines")
Entity Framework .Include(o => o.Customer)
Hibernate / JPA JOIN FETCH in JPQL, or an entity graph
ActiveRecord (Rails) .includes(:customer)
Laravel Eloquent ->with('customer')

So the Django example from earlier becomes:

1orders = Order.objects.filter(order_date__gte="2026-11-01").select_related("customer")
2
3for order in orders:
4    print(order.customer.customer_name)

Now the ORM runs a single query with a JOIN, and the loop doesn't go back to the database.

Watch the Video

I explain the N+1 problem in more detail, with a demo of the three fixes, in this video:

Summary

The N+1 query problem happens when your application runs one query to get a list, then one more query for every row in that list. It's easy to miss in development and often shows up only when your data grows.

To fix it:

  • Use a JOIN to get everything in one query
  • Load related rows in a single batch with IN
  • Use your ORM's eager loading feature

So, the next time a page is slow, check how many queries it's running, not just how long each one takes.

If you have any questions about the N+1 problem, let me know in the comments below.

Ben Brumm photo

Ben Brumm

Oracle SQL Certified Expert with 20+ years of experience in databases and business analysis, and 100,000+ YouTube subscribers.