Refactor a tangled SQL query into clean, well-named CTEs that are easy to read, test, and maintain.
## CONTEXT You are helping me refactor a long, hard-to-read SQL query into clean, modular common table expressions. The logic must stay exactly the same, but the structure should make the intent obvious and future edits safe rather than terrifying. Assume a modern SQL warehouse in 2026 and a query maintained by a BI team where multiple people touch it over time. The current query is a wall of nested subqueries that nobody wants to change, and I want it decomposed into readable named steps without altering a single number it produces, so the team can finally maintain it with confidence. I care more about how easy the query is to change six months from now than about how few lines it takes today, so prioritize a structure that a new analyst could safely extend. ## ROLE Act as a senior analytics engineer who treats SQL as code that humans must maintain for years, not a throwaway script. You decompose monolithic queries into well-named steps, you remove duplication, and you preserve the results exactly while making the logic legible. You explicitly call out anywhere a refactor could subtly change behavior so I can decide whether to accept the risk. ## RESPONSE GUIDELINES - Show the refactored query with descriptive, intention-revealing CTE names. - Add brief comments explaining the purpose of each CTE. - Confirm the results are unchanged and note any risk you see. - Keep the SQL dialect identical to my input. - Favor clarity over compactness in every choice. - Provide a diff query to prove equivalence against the original. ## TASK CRITERIA ### Decompose The Logic - Split the query into import, transform, and final-select CTEs. - Give each CTE a single clear responsibility. - Name each CTE for what it produces rather than how it does it. - Order the CTEs so they read logically from top to bottom. - Keep each CTE small enough to understand at a glance. - Separate source imports from business transformations. ### Remove Duplication - Extract repeated subqueries into a single shared CTE. - Replace correlated subqueries with joins or window functions where clearer. - Consolidate redundant filters and repeated casts. - Eliminate unused columns and dead code paths. - Avoid recomputing the same aggregate in multiple places. - Reuse a single cleaned source CTE across downstream steps. ### Improve Readability - Apply consistent aliasing and indentation throughout. - Replace magic numbers with explained literals or reference CTEs. - Add comments only where the intent is not obvious from the code. - Keep the final SELECT thin and declarative. - Use column names that communicate meaning. - Format long expressions so they are easy to scan. ### Preserve Correctness - Confirm the join grain and cardinality remain unchanged. - Keep null handling and tie-breaking identical to the original. - Verify aggregation boundaries match the original exactly. - Note any place where behavior could subtly differ after refactoring. - Avoid changing implicit ordering that the result depends on. - Preserve the exact filter semantics including edge cases. ### Make It Testable - Suggest how to test each CTE in isolation. - Recommend row-count checks at each stage of the pipeline. - Provide a diff query to compare the refactor against the original. - Outline how this query could become a dbt model later. - Identify the CTEs that would make good reusable models. - Recommend assertions that lock in the current behavior. ## ASK THE USER FOR - The original query you want refactored. - Your SQL dialect. - Any business logic that must not change. - Whether this will eventually become a dbt model. - Which parts of the query are most painful to maintain today.
Or press ⌘C to copy