Joins and the N+1 Query Trap

Joins and the N+1 Query Trap in PHP: --- A company keeps two filing rooms: one holds a card for every employee, the other holds a folder for every project.


The Analogy: The Records Clerk and the Filing Rooms

A company keeps two filing rooms: one holds a card for every employee, the other holds a folder for every project. A manager asks the records clerk for "each employee and the projects they are on". A patient, thorough clerk walks to the employee room, pulls all the cards, and then -- for each and every employee -- walks separately to the project room to look up that one person's projects. With three employees that is one trip for the cards plus three more trips for the projects: four journeys down the corridor. A join is the alternative: the clerk asks the filing system to cross-reference the two rooms once and hand back a single combined list, matching each employee to their projects in one pass.

The cross-reference has different flavours. An inner join returns only employees who have at least one project -- anyone with no project simply does not appear. A left join keeps every employee and shows their projects where they exist, leaving a blank (a null) for those with none. Choosing between them is choosing whether "people with nothing matched" should vanish or should still be listed with an empty result.

The clerk can also ask the filing system to tally as it cross-references: "for each employee, how many projects". That is a join combined with a grouped count, and it returns one row per employee with a number attached, computed in a single sweep rather than by the clerk counting folders by hand for each person.

The failure mode is the clerk who never learns the cross-reference and always walks the corridor once per employee. With three employees the waste is unnoticeable, but with three thousand it is three thousand and one separate journeys, and the manager waits all afternoon. This is the N+1 query problem: one query to fetch a list, then one more query for each item in that list. It hides perfectly in testing with a handful of rows and only reveals itself as a crippling slowness once real data arrives. The corridor was never the problem; walking it thousands of times was.


Syntax or Core Structure

An INNER JOIN matches rows from two tables on a shared key and returns only the pairs that match. You qualify columns with table aliases to keep the query readable.

<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT)');
$pdo->exec('CREATE TABLE books (id INTEGER PRIMARY KEY, author_id INTEGER, title TEXT)');
$pdo->exec("INSERT INTO authors VALUES (1,'Ada'),(2,'Ben'),(3,'Cara')");
$pdo->exec("INSERT INTO books VALUES (1,1,'Engines'),(2,1,'Notes'),(3,2,'Travels')");

$sql = 'SELECT a.name AS author, b.title AS title
        FROM books b
        INNER JOIN authors a ON a.id = b.author_id
        ORDER BY b.id';
foreach ($pdo->query($sql) as $r) {
    echo $r['author'], ': ', $r['title'], "\n";
}

Output:

Ada: Engines
Ada: Notes
Ben: Travels

The join matches each book to its author via a.id = b.author_id, producing one row per book with the author's name attached. Ada wrote two books and Ben one, so three rows come back. Cara wrote nothing, and because this is an inner join she does not appear at all -- a fact that becomes important when you actually want to list everyone.


Technical Depth: Join Types, the N+1 Trap, and Its Fix

Inner versus left join

The two joins you will reach for most differ in how they treat unmatched rows. An inner join drops rows with no match; a left join keeps every row from the left table, filling unmatched columns with null. Pairing a left join with COUNT and GROUP BY gives a per-row tally that correctly reports zero for rows with nothing matched.

JoinKeeps unmatched left rows?Typical use
INNER JOINNoOnly rows present in both tables
LEFT JOINYes (null on the right)Lists that must include everyone
LEFT JOIN + COUNT + GROUP BYYes (count 0)Per-row totals including zeros
<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT)');
$pdo->exec('CREATE TABLE books (id INTEGER PRIMARY KEY, author_id INTEGER, title TEXT)');
$pdo->exec("INSERT INTO authors VALUES (1,'Ada'),(2,'Ben'),(3,'Cara')");
$pdo->exec("INSERT INTO books VALUES (1,1,'Engines'),(2,1,'Notes'),(3,2,'Travels')");

$sql = 'SELECT a.name AS author, COUNT(b.id) AS n
        FROM authors a
        LEFT JOIN books b ON b.author_id = a.id
        GROUP BY a.id
        ORDER BY a.name';
foreach ($pdo->query($sql) as $r) {
    echo $r['author'], ' has ', $r['n'], "\n";
}

Output:

Ada has 2
Ben has 1
Cara has 0

Because the left join starts from authors, every author appears even with no books. COUNT(b.id) counts non-null book ids per group, so Cara correctly shows zero rather than vanishing. Had this been an inner join, Cara would be missing entirely -- exactly the bug that makes "why is this person not in the report" so hard to spot.

The N+1 trap

The classic mistake is to fetch a list and then loop, issuing one extra query per item. It looks innocent and produces correct results, but the query count grows with the data.

<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT)');
$pdo->exec('CREATE TABLE books (id INTEGER PRIMARY KEY, author_id INTEGER, title TEXT)');
$pdo->exec("INSERT INTO authors VALUES (1,'Ada'),(2,'Ben'),(3,'Cara')");
$pdo->exec("INSERT INTO books VALUES (1,1,'Engines'),(2,1,'Notes'),(3,2,'Travels')");

$queries = 0;

$authors = $pdo->query('SELECT id, name FROM authors ORDER BY id')->fetchAll();
$queries++;

$byAuthor = $pdo->prepare('SELECT COUNT(*) FROM books WHERE author_id = ?');
foreach ($authors as $a) {
    $byAuthor->execute([$a['id']]);
    $queries++;
    $n = (int) $byAuthor->fetchColumn();
    echo $a['name'], ': ', $n, "\n";
}
echo 'queries issued: ', $queries, "\n";

Output:

Ada: 2
Ben: 1
Cara: 0
queries issued: 4

One query fetches the three authors, then the loop fires one more query per author: 1 + 3 = 4 round trips. With three authors this is trivial, but with ten thousand it is ten thousand and one queries, each with its own network latency. The results are perfectly correct, which is precisely why the problem survives code review and only bites in production. This pattern is especially insidious with ORMs, where accessing a related property inside a loop -- $author->books -- can silently issue a fresh query each time without any visible prepare or execute in your code, so the N+1 hides behind ordinary-looking property access.

Fixing it by batching

The cure is to fetch the related data in one additional query and assemble the result in PHP, keeping the total at two queries regardless of list size.

<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT)');
$pdo->exec('CREATE TABLE books (id INTEGER PRIMARY KEY, author_id INTEGER, title TEXT)');
$pdo->exec("INSERT INTO authors VALUES (1,'Ada'),(2,'Ben'),(3,'Cara')");
$pdo->exec("INSERT INTO books VALUES (1,1,'Engines'),(2,1,'Notes'),(3,2,'Travels')");

$queries = 0;

$authors = $pdo->query('SELECT id, name FROM authors ORDER BY id')->fetchAll();
$queries++;

$counts = [];
foreach ($pdo->query('SELECT author_id FROM books') as $row) {
    $counts[$row['author_id']] = ($counts[$row['author_id']] ?? 0) + 1;
}
$queries++;

foreach ($authors as $a) {
    echo $a['name'], ': ', $counts[$a['id']] ?? 0, "\n";
}
echo 'queries issued: ', $queries, "\n";

Output:

Ada: 2
Ben: 1
Cara: 0
queries issued: 2

Now one query fetches the authors and a second fetches all books at once; the per-author counts are tallied in a PHP array keyed on author_id. The output is identical, but the query count is fixed at two whether there are three authors or three million. Often a single grouped join query does the whole job, but this two-query batch is the general shape of the fix when the relationship is more complex than a count.


Real World Example: A Blog Overview in One Query

A blog's front page lists each post with its comment count. The naive version fetches posts, then queries comments for each post -- textbook N+1. The correct version uses a single LEFT JOIN with GROUP BY, returning every post (including those with no comments) and its count in one query.

<?php
declare(strict_types=1);

final class Blog
{
    public function __construct(private PDO $pdo)
    {
        $this->pdo->exec('CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT)');
        $this->pdo->exec('CREATE TABLE comments (id INTEGER PRIMARY KEY, post_id INTEGER, body TEXT)');
        $this->pdo->exec("INSERT INTO posts VALUES (1,'Hello'),(2,'Second'),(3,'Quiet')");
        $this->pdo->exec("INSERT INTO comments VALUES
            (1,1,'hi'),(2,1,'great'),(3,1,'thanks'),(4,2,'ok')");
    }

    public function overview(): array
    {
        $sql = 'SELECT p.id, p.title, COUNT(c.id) AS comments
                FROM posts p
                LEFT JOIN comments c ON c.post_id = p.id
                GROUP BY p.id
                ORDER BY comments DESC, p.id';
        return $this->pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    }
}

$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$blog = new Blog($pdo);

foreach ($blog->overview() as $row) {
    echo $row['title'], ' (', $row['comments'], ")\n";
}

Output:

Hello (3)
Second (1)
Quiet (0)

One query does everything: the LEFT JOIN attaches comments to posts, GROUP BY p.id collapses each post to one row, and COUNT(c.id) tallies its comments. Because it is a left join, the "Quiet" post with no comments still appears with a count of zero rather than dropping out. Ordering by comments DESC puts the busiest post first. No matter how many posts exist, this remains a single database round trip.

The design flaw is that COUNT(c.id) scales with total comments, not posts, and this pattern quietly degrades when you extend it. Suppose the front page later needs to show the two most recent comment authors per post as well. A join that also pulls comment rows multiplies posts by comments -- a post with a thousand comments returns a thousand joined rows -- and GROUP_CONCAT or window functions become necessary to avoid shipping enormous result sets back to PHP only to discard most of them. The single-query join is exactly right for an aggregate like a count, but it is not a universal hammer: once you need a bounded slice of the related rows per parent (the "top N per group" problem), a plain join over-fetches badly, and the batched two-query approach or a window function is the better tool. Reaching for a bigger join every time is how a fast overview page slowly turns into a memory-hungry one.


Common Mistakes

  1. Looping to fetch related rows. Fetching a list and then querying inside the loop is the N+1 trap. Batch the related data into one extra query, or use a join.
  1. Using an inner join when you need everyone. An inner join silently drops rows with no match, so "people with zero of something" disappear. Use a left join when the unmatched rows must still appear.
  1. Counting the wrong column in a left join. COUNT(*) counts rows including the null-filled ones, so a row with no match shows 1 instead of 0. Count the joined table's key, COUNT(c.id), to get a true zero.
  1. Forgetting GROUP BY with an aggregate. Mixing COUNT with plain columns without grouping produces undefined or single-row results. Group by the key you want one row per.
  1. Not qualifying column names. When two tables share a column name like id, an unqualified reference is ambiguous. Use table aliases and qualify every column in a join.
  1. Assuming a join is always faster. A join that pulls many related rows per parent can over-fetch massively. For a bounded slice per parent, a batched query or window function beats a naive join.
  1. Testing only with tiny data. N+1 is invisible with three rows and catastrophic with three million. Test query counts and performance with realistic data volumes.
  1. Ignoring indexes on join keys. Joining on an unindexed foreign key forces a full scan. Index the columns you join and filter on so the database can match efficiently.
  1. Building a "top N per group" with a plain join. Joining then trimming in PHP fetches everything first. Use a window function or a per-parent limited subquery to fetch only what you need.

Best Practices

  • Reach for a single join, or a two-query batch, instead of querying inside a loop, so the query count does not grow with the data.
  • Choose a left join when the result must include rows that have nothing matched, and count the joined key to report a true zero.
  • Alias your tables and qualify every column, keeping joins readable and free of ambiguity.
  • Add indexes to the foreign-key columns you join and filter on, so the database matches rows without scanning.
  • Measure the number of queries a page issues, treating a count that scales with rows as a bug to fix before it reaches production.
  • Use a grouped aggregate join for counts and sums, where one row per parent is exactly what you want.
  • For a bounded slice of related rows per parent, prefer a window function or a batched follow-up query over a join that over-fetches.
  • Test with realistic data volumes so performance problems that hide behind small fixtures surface during development.

Practice Exercises

  1. Create customers and orders tables and write an INNER JOIN that lists each order with its customer name, confirming that customers with no orders do not appear.
  1. Rewrite the query as a LEFT JOIN with COUNT and GROUP BY so every customer appears with their order count, including a customer with zero orders showing 0.
  1. Deliberately write the N+1 version -- fetch customers, then loop querying each customer's order count -- and add a counter that prints how many queries were issued.
  1. Fix the N+1 by fetching all orders in one query and tallying counts per customer id in a PHP array, and show that the query count is now fixed at two regardless of how many customers there are.