Refactor Nested Subqueries Into Clean CTEs
Restructures a tangled query into readable, named CTEs without changing results, and documents each step.
Prompt
ROLE: You are a SQL reviewer who refactors for readability and maintainability while guaranteeing identical output. CONTEXT: The query below is hard to read (deeply nested subqueries, repeated logic, unclear intent). Schema: [SCHEMA]. Engine: [DATABASE_ENGINE]. ```sql [MESSY_QUERY] ``` TASK: 1. Identify repeated or deeply nested logic that should become named CTEs. 2. Rewrite the query as a top-to-bottom pipeline of CTEs, each with a descriptive name and a one-line comment stating its purpose. 3. De-duplicate any logic computed in more than one place. 4. Keep the final result set byte-for-byte equivalent; note any place where readability and exact equivalence conflict and how you resolved it. 5. Provide a quick way to diff old vs new output (EXCEPT/MINUS both directions, plus row counts). OUTPUT FORMAT: Refactor notes -> Cleaned ```sql``` (CTE pipeline) -> Equivalence-diff query -> What changed and what did not. CONSTRAINTS: Do not change column names, order, or filtering semantics. Avoid materialization that changes NULL/duplicate behavior. If the engine does not inline CTEs efficiently, note the potential performance tradeoff. Comment every CTE.
How to use this prompt
- 1
Copy the prompt above and paste it into ChatGPT, Claude, or Gemini — or open it in the visual Studio to edit each part on a canvas and run it with your own key.
- 2
Replace any bracketed placeholders with your specifics. The more concrete your context and constraints, the sharper the result — see the 5-part prompt structure.
- 3
Run it, then refine. Ask the model to critique and improve its own answer with self-critique prompting.
Techniques in this prompt
Assigns the model an expert persona so it adopts the right vocabulary, depth, and standards for the task.
Learn this techniqueForces explicit intermediate reasoning instead of jumping to a conclusion, which improves accuracy on hard tasks.
Learn this techniqueHas the model critique its own draft against criteria, then revise — raising quality in a single pass.
Learn this techniqueRecommended models
Build on this prompt
Open it in the visual Studio to wire it into a full workflow with your own API key — or learn the craft behind prompts like this.
More in Data Analysis & SQL
Translate Business Questions Into SQL
Turns a plain-English stakeholder question into a correct, well-commented SQL query against a known schema.
Optimize A Slow SQL Query
Diagnoses why a query is slow and rewrites it with targeted, explained optimizations and an index plan.
Debug A SQL Query That Returns Wrong Results
Systematically finds the logic error producing incorrect numbers and delivers a corrected, verified query.
Explain An Unfamiliar SQL Query In Plain English
Reverse-engineers a complex inherited query into a clear narrative, business meaning, and risk list.