Menu
Coddy logo textTech

NULLIF and IIF

Part of the Beyond the Basics section of Coddy's SQL journey — lesson 4 of 27.

Two more conditional helpers, both small and useful.

NULLIF(a, b) returns NULL when a = b, otherwise a. The classic use is guarding against division by zero:

SELECT total / NULLIF(count, 0) AS average
FROM stats

If count is zero we get NULL instead of an error.

IIF(cond, a, b) is a two-branch shortcut for CASE WHEN cond THEN a ELSE b END. Reach for it when the choice is binary; reach for CASE when there are more branches.

challenge icon

Challenge

Easy

Available tables and columns:

  • <strong>matches</strong>: <strong>id</strong>, <strong>shots</strong>, <strong>goals</strong>

For each match return:

  • id
  • conversion: goals * 1.0 / shots, but NULL when shots is 0 (use NULLIF)
  • verdict: 'win' when goals > 0, otherwise 'no goals' (use IIF)

Order by id.

Cheat sheet

NULLIF(a, b) returns NULL when a = b, otherwise returns a. Useful for avoiding division by zero:

SELECT total / NULLIF(count, 0) AS average
FROM stats

IIF(cond, a, b) is a shortcut for a two-branch CASE:

SELECT IIF(goals > 0, 'win', 'no goals') AS verdict
FROM matches

Try it yourself

SELECT id,
       -- conversion using NULLIF
       -- verdict using IIF
FROM matches
ORDER BY id
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Beyond the Basics