SQL reasoning means working out what a query returns before you run it. The fictional databases here are small enough to trace on paper.
This page sits inside database development and builds on joining related tables.
What are the four habits?
- Write the tables with their rows before reading the query.
- Follow the evaluation order: FROM, JOIN, WHERE, GROUP BY, HAVING, SELECT, ORDER BY.
- Count rows at each step.
- Predict edge cases: no match, empty group and missing value.
What is an example of reasoning?
A fictional table Sales has these rows: (Ampang, Bag, 45), (Ampang, Pen, 12), (Bangi, Bag, 50).
The query SELECT Branch FROM Sales WHERE Amount > 20; keeps two rows, then shows the Branch of each. The output is Ampang and Bangi, one row each, because only the Bag sales pass.
Move the filter and the answer changes. Filtering on Amount > 50 returns no rows at all, even though the table has three.
What are the lessons?
| Lesson | The skill |
|---|---|
| Predicting which rows a WHERE condition will include | filtering |
| Explaining why a join produces more rows than expected | row counts in joins |
| Distinguishing row filtering from group filtering | WHERE versus HAVING |
| Testing an aggregate query with empty groups and missing values | edge cases |
Then try the SQL reasoning practice set.
Who should start where?
A student new to queries should begin with WHERE. A student who can join but gets row counts wrong should start with the join lesson. A student who mixes up WHERE and HAVING should go straight to the filtering lesson.
If you want a teacher to watch you predict output, see online one-to-one Computer Science tuition. The one-hour trial class (from RM50) is a taught lesson on the topic you choose.