Question presented to candidate: "Our contacts table has optional nickname and phone columns, and our ad report divides clicks by impressions, which can be zero. Show me how COALESCE and NULLIF help with each, and explain how they relate to each other."
What a strong answer should cover:
COALESCE(a, b, ...)returns the first argument that is not NULL, scanning left to right; NULL only if all are NULLNULLIF(a, b)returns NULL whena = b, otherwisea; the classic uses are turning a sentinel ('',0) into NULL and avoiding division by zero- They combine:
COALESCE(NULLIF(TRIM(email), ''), 'no email'), andx / NULLIF(y, 0) - Both are standard shorthands for
CASE; COALESCE stops evaluating once it finds a value - Engine details: PostgreSQL raises
division by zeroand requires compatible argument types, SQLite returns NULL forx / 0and accepts mixed types; vendor variantsIFNULL(MySQL, SQLite) andISNULL(SQL Server) take two arguments and type the result differently
Code / implementation expected: Yes β a fallback chain with COALESCE and a safe ratio with NULLIF.
Schema used by the examples: