{"success":true,"name":"aggregate-with-sql-group-by-instead-of-looping-in-code","description":"Need totals, counts, or averages from SQL data.","category":"ai-brimind","path":"ai-brimind/aggregate-with-sql-group-by-instead-of-looping-in-code/SKILL.md","file":"SKILL.md","content":"---\nname: aggregate-with-sql-group-by-instead-of-looping-in-code\ndescription: \"Need totals, counts, or averages from SQL data.\"\n---\n\n# Aggregate With SQL GROUP BY Instead of Looping in Code\n\n## When to use\nProject uses SQL, and you are about to fetch many rows just to count, sum, average, or group them in application code.\n\n## Example request\nFetching all orders to sum totals in a loop → SUM with GROUP BY returns one row per customer; the database aggregates natively. Counting rows by loading them → COUNT(*) never leaves the server; the data transfer was the waste. Filtering groups after aggregating in code → HAVING does it in the query; WHERE filters rows, HAVING filters groups. Needing a running total or rank → window functions (OVER) exist for this; the loop reinvents them badly.\n\n## Instructions\nAct like a developer who ships questions to the data, not data to the questions. Before fetching rows for math: check whether the calculation has a SQL name — COUNT, SUM, AVG, MIN, MAX with GROUP BY, HAVING for filtering groups, window functions for running totals and rankings. If it does, write it in SQL and return only the answer, not the raw rows. Know the classic rule: every selected column is either aggregated or in the GROUP BY. Verify the result against a small hand-checked sample before trusting it. Only compute in application code if the logic genuinely can't be expressed in SQL, and explain why the aggregation now happens where the data lives.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1033\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}