Predict the Output
The other direction. You are handed a finished query and asked what the server will print — and the queries chosen are never the obvious ones. Almost every question in this shape is really a question about NULL.
1Arithmetic that touches NULL
select name, salary, bonus, salary + bonus from emp where deptno = 20;▶Show the answer
26000 + NULL is NULL, not 26000. NULL means “not known”, and a known number plus an unknown one is unknown. The row is still printed — only the computed column is empty.
2What the aggregates do with the same column
select count(*), count(bonus), sum(bonus), avg(bonus) from emp;▶Show the answer
Four numbers, three different behaviours. count(*) counts rows and gets twelve; count(bonus) counts values and gets nine; and avg divides by nine, not twelve — 25200 ÷ 9 = 2800. Writing 2100 here is the classic wrong answer.
3Does DISTINCT keep the NULL?
select distinct city from emp; — and state how many rows it has.▶Show the answer
Six rows, and NULL is one of them. distinct treats “no city recorded” as a distinct thing worth listing once, even though two employees have it. Answering “five” is the trap.
4One NULL poisons the whole string
select concat('Lambda', null);▶Show the answer
Not Lambda, and not an empty string — NULL. The same rule as the arithmetic in question 1: anything combined with an unknown is unknown.
5Negative numbers and half-way rounding
select mod(-17, 5), round(2.5), round(3.5), round(-2.5);▶Show the answer
mod takes the sign of the left operand, so mod(-17, 5) is -2 and not 3. And MySQL rounds a half away from zero: 2.5 to 3, -2.5 to -3. This is not the “round half to even” rule Python uses, so do not carry that habit across.
6Counting rows you never printed
emp has 12 rows and dept has 4. Write the output of select count(*) from emp, dept;▶Show the answer
No join condition means a cartesian product: 12 × 4 = 48. The examiner is checking that you noticed the missing where.
7A checklist for these questions
If yes, that is almost certainly the whole question.
Two tables and no where means a cartesian product.
Marks are given for the row count as well as the contents.
The heading of a computed column is the expression itself, unless an alias renames it.
A row has salary 26000 and bonus NULL. What does salary + bonus give?
A city column has 10 values across 6 distinct names, plus 2 NULLs. How many rows does SELECT DISTINCT city return?
What is mod(-17, 5) in MySQL?