{"success":true,"name":"spot-the-n-1-pattern-before-looping-sql-queries","description":"About to run a SQL query inside a loop over records.","category":"ai-brimind","path":"ai-brimind/spot-the-n-1-pattern-before-looping-sql-queries/SKILL.md","file":"SKILL.md","content":"---\nname: spot-the-n-1-pattern-before-looping-sql-queries\ndescription: \"About to run a SQL query inside a loop over records.\"\n---\n\n# Spot the N+1 Pattern Before Looping SQL Queries\n\n## When to use\nProject uses SQL (raw or via ORM), and you are writing code that fetches a list and then queries again for each item in it.\n\n## Example request\nFetch users, then loop fetching each user's orders → 1 query became 101; a JOIN or IN clause does it in one. ORM lazy-loading relations in a loop → each access fires a hidden query; eager loading (include/join fetch) is the built-in fix. Page feels fine with 10 rows → dies with 1,000; N+1 grows with data, not with code. Calling a helper that queries, inside a map → the query is hidden but still per-item; trace what each iteration actually executes.\n\n## Instructions\nAct like a developer who counts queries, not just lines of code. Before writing a loop that touches the database: state how many queries will run when the list has N items — if the answer grows with N, you have an N+1. Restructure to fetch in one shot: a JOIN, a WHERE id IN (...) batch, or your ORM's eager-loading feature — check the ORM's built-in mechanism before writing manual batching. Confirm by logging or counting the actual queries executed, not by reading the code. Only keep a per-item query if you can justify why batching is impossible here, and explain what the query count is now and why it no longer scales with the data.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1029\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}