Skip to the solution
EasyDSA11 min read

What do COALESCE and NULLIF do?

209 views

The problem

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 NULL
  • NULLIF(a, b) returns NULL when a = b, otherwise a; the classic uses are turning a sentinel ('', 0) into NULL and avoiding division by zero
  • They combine: COALESCE(NULLIF(TRIM(email), ''), 'no email'), and x / NULLIF(y, 0)
  • Both are standard shorthands for CASE; COALESCE stops evaluating once it finds a value
  • Engine details: PostgreSQL raises division by zero and requires compatible argument types, SQLite returns NULL for x / 0 and accepts mixed types; vendor variants IFNULL (MySQL, SQLite) and ISNULL (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:

  • coalesce
  • null

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the query and run it against the tables for this question.

SQLCOALESCE fallback chains, and NULLIF to treat blank strings as missing
SQLNULLIF(impressions, 0) makes the click-through rate safe, COALESCE picks what to show
SQLCOALESCE changes what an average means: skip unknown budgets or count them as 0
PostgreSQL: NULLIF prevents the division by zero error
SELECT name,
       ROUND(clicks * 100.0 / NULLIF(impressions, 0), 2) AS ctr_pct,
       COALESCE(budget::text, 'not set') AS budget_label
FROM campaigns
ORDER BY id;

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 13 of 82 in SQL

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All SQL questions
Up nextEasy

What is a CHECK constraint?

Continue