Hint: Replace NULLs with zero before AVG to include them [OK]
Common Mistakes:
Ignoring NULLs and averaging only non-NULL values
Assuming AVG ignores zeros
Miscounting number of rows
4. Identify the error in this query that tries to count all rows including NULLs in score column:
SELECT COUNT(score) + COUNT(NULL) FROM results;
medium
A. The query sums counts correctly
B. COUNT(score) counts all rows including NULLs
C. COUNT(NULL) counts NULLs as 1
D. COUNT(NULL) returns 0
Solution
Step 1: Understand COUNT(NULL) behavior
COUNT(NULL) always returns 0 because the NULL expression is always NULL and thus never counted.
Step 2: Analyze COUNT(score)
COUNT(score) counts only non-NULL values in score column, not all rows.
Final Answer:
COUNT(NULL) returns 0 -> Option D
Quick Check:
COUNT(NULL) always returns 0 [OK]
Hint: COUNT(NULL) always returns zero, use COUNT(*) for all rows [OK]
Common Mistakes:
Thinking COUNT(NULL) counts NULLs
Assuming COUNT(column) counts NULLs
Adding COUNT(NULL) to count rows
5. You have a table employees with a nullable bonus column. You want to calculate the total bonus, treating NULL as zero, but only for employees with a salary above 50000. Which query correctly does this?
hard
A. SELECT SUM(COALESCE(bonus, 0)) FROM employees WHERE salary > 50000;
B. SELECT SUM(bonus) FROM employees WHERE COALESCE(salary, 0) > 50000;
C. SELECT SUM(COALESCE(bonus, 0)) WHERE salary > 50000 FROM employees;
D. SELECT SUM(bonus) FROM employees WHERE salary > 50000;
Solution
Step 1: Use COALESCE to treat NULL bonus as zero
SUM(COALESCE(bonus, 0)) replaces NULL bonuses with 0 before summing.
Step 2: Filter employees with salary > 50000
The WHERE clause correctly filters rows before aggregation.
Step 3: Check query syntax
SELECT SUM(COALESCE(bonus, 0)) FROM employees WHERE salary > 50000; has correct syntax.
Final Answer:
SELECT SUM(COALESCE(bonus, 0)) FROM employees WHERE salary > 50000; -> Option A
Quick Check:
Use COALESCE in SUM and filter with WHERE [OK]
Hint: Use COALESCE in SUM and filter rows with WHERE [OK]