DAT-11Recommended
Load related rows in one query
Never run one query per item in a list. Load related rows together with a join or one IN query.
How to do it
Watch for loops that call the database, often hidden behind lazy loading in an ORM. Use the ORM's eager loading, a join, or one query with WHERE id = ANY($1). Count queries per request in development. A trace shows the repeated queries, as Trace requests across services explains.
Examples
JavaScript example
// Bad: 1 query for orders, then 1 per order
for (const order of orders) order.customer = await db.one('SELECT * FROM customers WHERE id = $1', [order.customer_id]);
// Good: 2 queries in total
const customers = await db.many('SELECT id, name FROM customers WHERE id = ANY($1)', [orders.map(o => o.customer_id)]);
Python example
# Good in Python: 2 queries in total
customer_ids = [order.customer_id for order in orders]
cursor.execute("SELECT id, name FROM customers WHERE id = ANY(%s)", (customer_ids,))
How to check
A test loads a list with 5 items and with 50, counting the queries through the driver's query hook or log. Both counts are equal.
Sources
Related rules
- OPS-15 Trace requests across services in Operations and observability
- STK-31 Use a mature ORM for database code in Software choices
- SCL-5 Make one server fast before you add more in Scaling
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/queries-and-indexes/no-n-plus-one">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.