Debugging SQL Queries
Learning Objectives
- You can debug SQL syntax errors and unexpected results systematically.
- You can build queries incrementally instead of guessing.
When a query fails, there are two common possibilities:
- The query is invalid SQL
- The query runs, but the result is not what you expected
Both are normal. The important skill is to debug them methodically.
Start Small
A good debugging habit is to start from the smallest useful query.
SELECT *
FROM courses;
Then add one feature at a time:
- Choose only needed columns
- Add a
WHEREclause - Add sorting
- Add a limit
This makes it much easier to see where things went wrong.
Read the Error Message
If the database reports a syntax error, read the message carefully. It often points near the place where the parser became confused.
Typical causes include:
- A missing comma
- A misspelled column name
- A table name that does not exist
- Quotes used incorrectly
Compare Expectation with Result
Sometimes a query is valid, but still wrong.
For example, maybe it returns too many rows because OR should have been AND. Or maybe it returns no rows because the filter value does not actually exist.
In those cases, ask:
- What did I expect?
- What rows did I actually get?
- Which part of the query is responsible for the mismatch?
A Short Debugging Checklist
When a query behaves strangely, try this order:
- confirm the table and column names,
- remove extra clauses and simplify the query,
- inspect the actual returned rows,
- compare the result with what you expected,
- add complexity back one step at a time.
Even small checks help. For example:
SELECT
id,
submitted_at,
status
FROM submissions;
or
SELECT DISTINCT status
FROM submissions;
These quick checks often reveal whether the problem is in the data, in the assumptions, or in the query.
Check Your Understanding
- Why is it useful to remove complexity from a query while debugging?
- Why should you inspect the actual returned rows instead of trusting your intention?
- Why are small checks helpful when a query behaves unexpectedly?
SQL Practice
Complete the SQL sequence below to practice fixing broken queries systematically.