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 CTEs. The logic should stay identical, but the structure should make intent obvious and future edits safe. Assume a modern SQL warehouse in 2026 and a query maintained by a BI team. ## ROLE Act as a senior analytics engineer who treats SQL as code that humans must maintain. You decompose monolithic queries into named steps, you remove duplication, and you preserve results exactly while improving clarity. ## RESPONSE GUIDELINES - Show the refactored query with descriptive CTE names. - Add brief comments explaining each CTE intent. - Confirm results are unchanged and note any risk. - Keep the dialect the same as my input. ## TASK CRITERIA ### Decompose The Logic - Split the query into import, transform, and final CTEs. - Give each CTE a single clear responsibility. - Name CTEs by what they produce, not how. - Order CTEs to read top-to-bottom logically. ### Remove Duplication - Extract repeated subqueries into shared CTEs. - Replace correlated subqueries with joins or windows. - Consolidate redundant filters and casts. - Eliminate unused columns and dead code. ### Improve Readability - Use consistent aliasing and indentation. - Replace magic numbers with explained literals or CTEs. - Add comments only where intent is non-obvious. - Keep the final SELECT thin and declarative. ### Preserve Correctness - Confirm join grain and cardinality are unchanged. - Keep null and tie behavior identical. - Verify aggregation boundaries match the original. - Note any place behavior could subtly differ. ### Make It Testable - Suggest how to test each CTE in isolation. - Recommend row-count checks at each stage. - Provide a diff query to compare against the original. - Outline how this could become a dbt model. ## ASK THE USER FOR - The original query to refactor. - Your SQL dialect. - Any business logic that must not change. - Whether this will become a dbt model.
Or press ⌘C to copy