{"success":true,"name":"use-sql-case-to-compute-categories-in-one-query-not-many","description":"Running several similar SQL queries that differ only by condition.","category":"ai-brimind","path":"ai-brimind/use-sql-case-to-compute-categories-in-one-query-not-many/SKILL.md","file":"SKILL.md","content":"---\nname: use-sql-case-to-compute-categories-in-one-query-not-many\ndescription: \"Running several similar SQL queries that differ only by condition.\"\n---\n\n# Use SQL CASE to Compute Categories in One Query, Not Many\n\n## When to use\nProject uses SQL, and you are about to run multiple near-identical queries (one per status, per range, per category) and combine the results in code.\n\n## Example request\nThree COUNT queries for small/medium/large orders → one query with CASE buckets does it in a single pass; the table was scanned three times for one answer. Fetching rows to categorize them in a loop → CASE WHEN in the SELECT computes the label where the data lives; the transfer was the waste. Counting matches per condition → SUM(CASE WHEN cond THEN 1 ELSE 0 END) — or FILTER where supported — is conditional aggregation, the named pattern for exactly this. CASE with overlapping conditions → the first match wins silently; branch order is logic, not style.\n\n## Instructions\nAct like a developer who notices when several queries are one query wearing disguises. When results differ only by a condition — counts per status, sums per bucket, labels per range — collapse them into a single query using CASE expressions: derive categories in the SELECT, and use conditional aggregation (SUM(CASE WHEN ... THEN 1 ELSE 0 END), or the engine's FILTER clause) to compute all branches in one table pass. Order CASE branches knowing evaluation stops at the first match, and always decide the ELSE — unhandled rows becoming NULL should be a choice, not a surprise. Verify the combined query against the separate ones' results before deleting them. Only finalize once one pass produces what N queries did, and each branch's condition and fallback is explicit.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1140\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}