{"success":true,"name":"diagnose-duplicate-rows-before-reaching-for-sql-distinct","description":"A SQL query returns duplicates and DISTINCT seems like the fix.","category":"ai-brimind","path":"ai-brimind/diagnose-duplicate-rows-before-reaching-for-sql-distinct/SKILL.md","file":"SKILL.md","content":"---\nname: diagnose-duplicate-rows-before-reaching-for-sql-distinct\ndescription: \"A SQL query returns duplicates and DISTINCT seems like the fix.\"\n---\n\n# Diagnose Duplicate Rows Before Reaching for SQL DISTINCT\n\n## When to use\nProject uses SQL, and a query shows repeated rows, and you are about to slap DISTINCT (or dedupe in code) without knowing where the duplication comes from.\n\n## Example request\nDISTINCT added and the report 'works' → the one-to-many JOIN still multiplies rows underneath; the symptom was hidden, not explained. Aggregates suddenly wrong → SUM ran on the multiplied rows before DISTINCT could help; JOIN fan-out corrupts math silently. Duplicates only for some records → those parents have multiple children; the relationship's cardinality was the cause. DISTINCT made the query slow → it sorts everything to dedupe; an EXISTS instead of a JOIN removed the duplication at the source.\n\n## Instructions\nAct like a detective who asks why the duplicates exist before making them disappear. When a query returns repeated rows: first find the source — usually a JOIN to a one-to-many table fanning out the parent rows. Confirm by checking the relationship's cardinality and inspecting a duplicated example. Then fix at the source: use EXISTS when you only need to test presence, aggregate the many-side before joining, or join a pre-grouped subquery — so aggregates and counts stay correct. Reserve DISTINCT for cases where you can explain exactly why duplicates are legitimate and harmless to collapse. Only finalize once you can state the cause of the duplication and why the chosen fix removes it rather than masks it.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1069\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}