Video in progress

What does the N+1 query problem look like from the database's side, and how do you solve it at the SQL level?

One query fetches N main records, then a separate query runs for each of them: N+1 in total. On the database it shows up as hundreds of small queries of the same shape that differ only in the parameter. The fix is to fetch the related data in one or two queries with a JOIN or IN (...).

📖 Answer

In the application log (or in pg_stat_statements) the picture looks like this:

SELECT * FROM orders WHERE created_at > '2026-11-01';   -- 200 rows
SELECT * FROM users WHERE id = 17;
SELECT * FROM users WHERE id = 23;
SELECT * FROM users WHERE id = 17;
... 197 more

Even if each query takes 1 ms, with the network the page stretches to 300-400 ms. You don't notice it on a local database, but it shows up right away on prod, where the database sits on another server.

There are two ways at the SQL level:

-- 1) a single JOIN
SELECT o.*, u.email
FROM orders o JOIN users u ON u.id = o.user_id
WHERE o.created_at > '2026-11-01';

-- 2) two queries: orders first, then the set of users you need
SELECT * FROM users WHERE id = ANY(?);   -- [17, 23, 31, ...]

In JPA this usually comes from touching a lazy association inside a loop. The fixes: JOIN FETCH, @EntityGraph, or hibernate.default_batch_fetch_size (it does the second option automatically).

To catch it, turn on SQL logging in dev, or check the query count in a test: "this endpoint must not run more than 3 queries".