{"success":true,"name":"prevent-duplicate-rows-with-sql-upserts-not-check-then-inser","description":"Writing SQL logic like 'insert if it doesn't already exist'.","category":"ai-brimind","path":"ai-brimind/prevent-duplicate-rows-with-sql-upserts-not-check-then-inser/SKILL.md","file":"SKILL.md","content":"---\nname: prevent-duplicate-rows-with-sql-upserts-not-check-then-inser\ndescription: \"Writing SQL logic like 'insert if it doesn't already exist'.\"\n---\n\n# Prevent Duplicate Rows With SQL Upserts, Not Check-Then-Insert\n\n## When to use\nProject uses SQL, and you are about to SELECT to check existence and then INSERT or UPDATE based on the result.\n\n## Example request\nSELECT then INSERT if empty → two requests pass the SELECT simultaneously and both insert; that's a race condition, not rare bad luck. Catching the duplicate error 'sometimes' → the database has a real answer; INSERT ... ON CONFLICT / ON DUPLICATE KEY is the built-in upsert. Deduping with a nightly cleanup job → a UNIQUE constraint prevents duplicates at write time; prevention beats cleanup. Counter updated with read-modify-write in code → UPDATE ... SET count = count + 1 is atomic; the database increments safely.\n\n## Instructions\nAct like a developer who assumes two copies of your code run the same line at the same instant. Whenever the logic is 'check, then write': recognize it as a race condition and reach for the database's atomic mechanism instead — a UNIQUE constraint plus INSERT ... ON CONFLICT (or ON DUPLICATE KEY UPDATE), or an atomic UPDATE expression for counters. The constraint is mandatory: without it, no upsert syntax can protect you. If your database or ORM version is unclear, check which upsert syntax it supports rather than guessing. Only ship once the write is a single atomic statement guarded by a constraint, and explain why concurrent requests can no longer create duplicates.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1034\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}