Video in progress
What do `COALESCE` and `NULLIF` do? How do you use them to avoid a division by zero error?
COALESCE(a, b, c) returns the first non-NULL value, and NULLIF(a, b) returns NULL if a = b. x / NULLIF(y, 0) returns NULL instead of an error on division by zero, and you can then turn that into 0 with COALESCE.
📖 Answer
Both are small, but you need them every day in reporting queries.
SELECT name,
COALESCE(phone, email, 'aloqa yo''q') AS contact
FROM customers;
NULLIF does the opposite: it turns a specific value into NULL. The classic case is calculating a conversion rate.
-- if visits = 0: ERROR: division by zero
SELECT orders * 100.0 / visits FROM daily_stats;
-- the safe version
SELECT COALESCE(orders * 100.0 / NULLIF(visits, 0), 0) AS conversion
FROM daily_stats;
One thing: 100.0 isn't written that way for nothing. If both columns are integer, orders * 100 / visits does integer division and gives 33 instead of 33.3.
Another use is treating an empty string as NULL: NULLIF(trim(middle_name), ''). It's handy for treating a '' from a form and a real NULL the same way.
Sign up to mark studied questions and save your progress.