Avoid N plus 1 queries with batching
Replace a query per row inside a loop with one query using ANY and a lookup Map, so loading 100 posts with authors takes 2 queries instead of 101.
An N+1 problem appears when you load a list with one query and then run another query for each item. The number of round trips grows with the list.
// N+1: one query for the posts, then one per post.
const { rows: posts } = await db.query('SELECT id, title, author_id FROM posts LIMIT 100');
for (const post of posts) {
const { rows } = await db.query('SELECT name FROM users WHERE id = $1', [post.author_id]);
post.author = rows[0].name;
}
// Batched: two queries in total.
const ids = [...new Set(posts.map((post) => post.author_id))];
const { rows: users } = await db.query('SELECT id, name FROM users WHERE id = ANY($1)', [ids]);
const names = new Map(users.map((user) => [user.id, user.name]));
for (const post of posts) post.author = names.get(post.author_id);
console.log(posts[0]);{ id: 1, title: 'Hello', author_id: 7, author: 'Ada' }The first version sends 101 statements for 100 posts; the second sends 2. = ANY($1) takes an array parameter in PostgreSQL's pg driver, and the Map joins the results to the posts in the application.
A SQL JOIN does the same in one query and is often simplest. The batching approach suits cases where the second lookup comes from another service or store. Libraries such as DataLoader batch automatically within one tick. See [ANY in PostgreSQL](https://www.postgresql.org/docs/current/functions-comparisons.html).