The most common performance bug in app code
Picture typical backend code showing authors and their books:
authors = query("SELECT id, name FROM authors") # 1 query for a in authors: books = query("SELECT title FROM books WHERE author_id = ?", a.id) # N queries
One query for the list, then one more per author. With 3 authors that is 4 queries. With 2,000 authors it is 2,001. This is the N+1 problem: the code looks innocent, works fine in testing with 5 rows, then melts in production, because every query pays network and planning overhead.
The fix is the tool you mastered in unit 5: one JOIN brings everything back in a single query, and the loop just formats rows it already has. Databases are extremely good at joins. Round trips are what kill you.
Code exercise · sql
Run it. The one JOIN query returns every author-book pair at once. The bookstore data here (authors, books, sales) is also your capstone dataset for the final lesson.
Quiz
A page shows 50 products, each with its category name, and the code runs 51 queries. What is the N+1 diagnosis and cure?
Problem
A dashboard lists 200 customers, then runs one extra query per customer to count their orders. How many queries does the page issue in total? Answer with a number.