The N+1 query problem

A page that lists 50 enlistments can ask the database 51 questions or 1 question. The number of queries decides how fast the page is.

The My courses page of the university's online enlistment system lists each course you enlisted in, with its title and schedule. Before it appears, the application server has asked the database for your enlistments and for the details of each course.

Your browserAsks for the page
Application serverBuilds the page
DatabaseHolds the rows
Think first. Suppose a page lists 50 enlistments and the server looks up each course title with a separate query. How many queries reach the database? Write down your number.
The usual answer is 50. The correct answer is 51, because the page first runs one query to fetch the enlistments. Collect numbers before anyone moves the slider.

Start with One query per row and move the slider. This slow pattern is the N+1 query problem. Then try One join and a cache, and compare.

Queries for one page
—
Most pages per second
—
How the page is built
More detail

The code behind each choice

The code is Django. The view (views.py) fetches rows from the database. The template (schedule.html) is the page layout, and it loops over the rows. Django calls the join select_related.

The first version looks correct, and AI tools often produce it when asked for a schedule page. It is still slow.

How the times are worked out

The model assumes each query takes 0.4 ms (milliseconds), because the database can answer it from an index, a lookup structure that the database keeps for finding rows quickly. It also assumes 24 ms of handler time that is not database work. Handler time is the total time the server spends on one request. A worker is a server process that handles one request at a time. The most pages per second is the number that 8 workers can finish.

Time in the database
—
Handler time
—

When a cache is a poor choice

A cache works well when the table is small and rarely changes. When the data changes often, you hold two copies of the same fact and one of them goes out of date. Normalization describes the same problem. How work grows with the list explains why the query count matters more as data grows.

With three rows in your test database, the page makes four queries and takes about 1.6 milliseconds, which nobody notices. The number of queries grows with the number of rows, and test data rarely has enough rows. The problem appears only in production, where the data is large and your tests do not run.

You can now count the queries a page makes and spot the N+1 problem.