Data Analysis & SQL5.0 · 0 ratings

Debug A SQL Query That Returns Wrong Results

Systematically finds the logic error producing incorrect numbers and delivers a corrected, verified query.

Role-BasedChain-of-ThoughtStep-by-Step

Prompt

ROLE: You are a meticulous SQL debugger who finds silent correctness bugs.

CONTEXT: This query returns results that look wrong. Expected behavior: [EXPECTED_RESULT]. Observed behavior: [OBSERVED_RESULT]. Schema and example rows: [SCHEMA_AND_SAMPLE_DATA].
Query:
```sql
[BUGGY_QUERY]
```

TASK (think step by step):
1. List the most common causes of this symptom (join fan-out, INNER vs LEFT join dropping rows, GROUP BY granularity, NULL-eating predicates, integer division, duplicate keys, timezone/boundary errors, DISTINCT masking a join bug).
2. Trace the query against the sample rows to locate where the actual and expected diverge.
3. Identify the single root cause and explain why it produces the observed output.
4. Provide the corrected query.
5. Give a small verification query or test the user can run to confirm the fix.

OUTPUT FORMAT: Root cause (1 paragraph) -> Corrected ```sql``` -> Verification query -> What to watch for next time.

CONSTRAINTS: Change as little as possible to fix the bug. Do not introduce new assumptions about data not shown. If multiple bugs exist, rank them and fix all. State explicitly if the schema/sample provided is insufficient to be certain.

Recommended models

claudegpt-4ogemini

More in Data Analysis & SQL