NULL Handling in Aggregate Functions: Mistakes
Module: Aggregate Functions & Grouping
SELECT AVG(bonus) FROM employees;
-- Expecting this to treat NULL as $0
SELECT AVG(COALESCE(bonus, 0)) FROM employees;
-- Explicitly treats NULL as $0
AVG(bonus) calculates average of only non-NULL bonuses. Use COALESCE to explicitly treat NULL as zero.
Use COALESCE(column, 0) if you want to treat NULL as zero in AVG or SUM
High
AVG ignores NULL values - does not treat them as zero
SELECT SUM(bonus) FROM employees;
-- Expecting 0 when all bonuses are NULL
SELECT COALESCE(SUM(bonus), 0) FROM employees;
-- Returns 0 when all bonuses are NULL
If all bonus values are NULL, SUM(bonus) returns NULL. Use COALESCE for NULL-safe arithmetic.
Wrap aggregates in COALESCE when you need NULL-safe results
High
SUM of all NULL values returns NULL, not 0