5. NULL handlingEasy
Table emp has rows: (Ann, eng), (Bo, eng), (Cy, ops), (Di, NULL). The headcount and the department count disagree. What does this return?
SELECT COUNT(*), COUNT(dept) FROM emp;
What does it output?
- 4, 4
- 4, 3
- 3, 3
- 4, 2
Show answer
Answer: B. 4, 3
COUNT(*) counts rows. COUNT(column) counts non-NULL values in that column, so Di's NULL department is skipped.
11. NULL handlingMedium
Table emp has rows: (Ann, eng), (Bo, eng), (Cy, ops), (Di, NULL). A report of everyone outside engineering comes up short. What does this return?
SELECT COUNT(*) FROM emp WHERE dept <> 'eng';
What does it output?
- 1
- 2
- 0
- 4
Show answer
Answer: A. 1
Comparing NULL with anything gives UNKNOWN, not TRUE, so Di is filtered out. Only Cy matches. Add OR dept IS NULL if you want Di included.
12. JoinsMedium
users: (1, Ann), (2, Bo), (3, Cy). orders(id, user_id, amount): (10, 1, 50), (11, 1, 20), (12, 2, 30). An orders-per-user report should include Cy with zero. What does it return?
SELECT u.name, COUNT(o.id)
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.name
ORDER BY u.name;
What does it output?
- Ann, 2
Bo, 1 - Ann, 2
Bo, 1
Cy, 0 - Ann, 2
Bo, 1
Cy, 1 - Ann, 1
Bo, 1
Cy, 0
Show answer
Answer: B. Ann, 2 / Bo, 1 / Cy, 0
LEFT JOIN keeps Cy with NULL order columns, and COUNT(o.id) skips NULLs, giving 0. COUNT(*) would count Cy's NULL row and report 1, a classic bug.
13. GroupingMedium
Table emp has rows: (Ann, eng), (Bo, eng), (Cy, ops), (Di, NULL). A per-department headcount includes a mystery row. What does SQLite return?
SELECT dept, COUNT(*) FROM emp
GROUP BY dept
ORDER BY dept;
What does it output?
- eng, 2
ops, 1 - NULL, 1
eng, 2
ops, 1 - eng, 2
ops, 1
NULL, 1 - eng, 3
ops, 1
Show answer
Answer: B. NULL, 1 / eng, 2 / ops, 1
GROUP BY puts all NULLs in one group (unlike =, which never matches NULL). SQLite and Postgres disagree on where NULLs sort: SQLite puts them first in ascending order, Postgres last. Use NULLS FIRST/LAST to be explicit.
14. NULL handlingMedium
Table t has a column x with values 10, NULL, 20. The average looks too high. What does this return?
SELECT SUM(x), AVG(x), COUNT(x) FROM t;
What does it output?
- 30, 10.0, 3
- 30, 15.0, 2
- NULL, NULL, 3
- 30, 15.0, 3
Show answer
Answer: B. 30, 15.0, 2
Aggregates ignore NULLs: the average is 30 / 2, not 30 / 3. If missing values should count as zero, write AVG(COALESCE(x, 0)).