SQL Query Debugger
Added Apr 2, 2026
About This Prompt
This prompt transforms ChatGPT into a SQL debugging assistant that systematically diagnoses and fixes problematic database queries. Whether your query returns wrong results, times out on large datasets, or produces unexpected NULLs, this prompt walks through a structured analysis covering logical errors, performance bottlenecks, and optimization opportunities. It is particularly valuable for developers who work with complex multi-table joins, aggregation queries, or legacy SQL that has grown unwieldy over time. The output includes a corrected query with explanatory comments, making it both a fix and a learning tool for improving your SQL skills going forward.
Variables to Customize
[SQL_QUERY]
The SQL query you need debugged or optimized
Example: SELECT u.name, COUNT(o.id) FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE o.status = 'completed' GROUP BY u.name
[DATABASE_SYSTEM]
The database engine you are using
Example: PostgreSQL 15
[EXPECTED_BEHAVIOR]
What the query should return
Example: all users with their completed order count, including users with zero orders
[ACTUAL_BEHAVIOR]
What the query actually does wrong
Example: users with zero orders are excluded from the results
Tips for Best Results
- Include the table schema or at least column types when dealing with type conversion issues
- Mention the approximate row counts for each table so the optimizer suggestions are realistic
- If you have an EXPLAIN output already, paste it alongside the query for deeper analysis
Example Output
**Issue Identified:** Your LEFT JOIN is being converted to an INNER JOIN because the WHERE clause filters on `o.status = 'completed'`. When a user has no orders, `o.status` is NULL, which fails the equality check. **Corrected Query:** ```sql SELECT u.name, COUNT(o.id) FROM users u LEFT JOIN orders o ON u.id = o.user_id AND o.status = 'completed' GROUP BY u.name; ``` The fix moves the filter condition into the JOIN clause so users without matching orders still appear with a count of 0.