Spot the bug
This endpoint is slow with many orders. Which line causes N+1?
import psycopgfrom psycopg.rows import TupleRowdef orders_with_items(conn: psycopg.Connection[TupleRow],) -> dict[int, list[str]]:orders = conn.execute("SELECT id FROM orders ORDER BY id LIMIT 500").fetchall()result: dict[int, list[str]] = {}for (order_id,) in orders:rows = conn.execute("SELECT sku FROM items WHERE order_id = %s", (order_id,)).fetchall()result[order_id] = [sku for (sku,) in rows]return result
Hint 1 of 1
Count the queries for 500 orders.
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 13
rows = conn.execute(
One query per order inside the loop: 1 + 500 round trips. Load all items at once with WHERE order_id = ANY(%s) and group them in Python.