{"success":true,"name":"break-complex-sql-into-named-cte-steps","description":"A SQL query has grown into deeply nested subqueries.","category":"ai-brimind","path":"ai-brimind/break-complex-sql-into-named-cte-steps/SKILL.md","file":"SKILL.md","content":"---\nname: break-complex-sql-into-named-cte-steps\ndescription: \"A SQL query has grown into deeply nested subqueries.\"\n---\n\n# Break Complex SQL Into Named CTE Steps\n\n## When to use\nProject uses SQL, and you are writing or debugging a query with multiple nested subqueries that's becoming hard to read or verify.\n\n## Example request\nFour levels of nested SELECTs → nobody can say what level two returns; WITH clauses give each step a name. Debugging by staring at the whole query → running each CTE alone isolates the wrong step; steps you can run are steps you can test. Same subquery pasted twice → they drift apart over time; one CTE, referenced twice. A CTE reused in a hot query is slow → some engines materialize CTEs; readability and the execution plan are separate checks.\n\n## Instructions\nAct like a writer who turns one tangled sentence into clear paragraphs. When a query nests beyond one level: restructure it with WITH (CTEs), giving each logical step a name that says what it produces (active_customers, monthly_totals). Build and verify incrementally — run each CTE by itself against a known sample before stacking the next on top; that's how you locate the wrong step instead of guessing. Replace repeated subqueries with a single named CTE. Afterward, check the plan with EXPLAIN, since some engines treat CTEs as optimization fences — readability must not silently cost performance in hot paths. Only finalize once each step is individually verified and the whole reads as a pipeline you could explain to a junior line by line.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1070\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}