Aggregate Questions
Five functions, and a paper almost always asks for at least one of them. The queries themselves are short; the marks are lost on what the functions do with the missing values, which is why half this page is about NULL.
1The five, on one table
▶Show the answer
“How many records/rows/employees” is always count(*). It counts rows and cannot be tripped up by a missing value anywhere in them.
▶Show the answer
▶Show the answer
A question asking for the name of the highest-paid employee is a different and much harder thing — select name, max(salary) from emp; does not do it, and MySQL refuses that query outright. The Find the Error page shows why.
▶Show the answer
Functions nest: avg() runs first and round() tidies the result. Papers like this one because it needs two ideas in one line.
2The trap: aggregates skip NULL
Every aggregate except count(*) ignores NULL. It does not treat it as zero — it leaves the row out of the calculation entirely. Three employees have no bonus, and you can watch it happen:
25200 ÷ 9 = 2800, which is what the server printed. 25200 ÷ 12 would be 2100. The average bonus is over the nine employees who have one, not over all twelve. If an examiner gives you a table with a blank and asks for an average, this is the whole question.▶Show the answer
The gap between the two numbers is exactly the number of NULLs in that column — twelve rows, nine bonuses, three missing.
3Counting the different values
▶Show the answer
Three, not four — and there are two separate reasons, both worth noticing. Lata Gurung’s deptno is NULL, so she is not counted; and department 40 (Research) exists in the dept table but has nobody in it, so it cannot appear in a query that only reads emp.
4Which function does the question want?
count(*)
count(column)
count(distinct column)
sum(column)
avg(column)
max(column) / min(column)
A column has 12 rows, 3 of them NULL, and the 9 values add up to 25200. What does avg(column) return?
Which aggregate counts rows rather than values, and so is never affected by NULL?