23. Conversion rates when the denominator is zero

SQLEasyNULL trap

division by zero · nullif · rates · nulls

How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

Marketing ranks campaigns by two rates: how often an ad is clicked, and how often a click turns into a signup.

Some campaigns were never shown, some were shown and never clicked, and for a few the click or signup tracking was broken, so the count is missing. The current report either stops with a division error or shows those campaigns with a rate of 0, which puts a campaign that was never shown at the bottom of the ranking next to the truly bad ones.

Input tables

campaign_stats

One row per campaign.

Column Type Description
campaign_id BIGINT Unique per campaign.
channel STRING search, social, email or display.
impressions BIGINT How many times the ad was shown. Never NULL, can be 0.
clicks BIGINT How many times it was clicked. NULL if click tracking was broken.
signups BIGINT How many signups followed. NULL if signup tracking was broken.

Requirement

Return both rates for every campaign.

  • click_rate is clicks divided by impressions.
  • signup_rate is signups divided by clicks.
  • A rate is NULL when it cannot be computed: the number it is divided by is 0 or NULL, or the number being divided is NULL.
  • A rate of 0 means something specific: the ad was shown (or clicked) and nothing followed. A campaign with 2,000 impressions and 0 clicks has click_rate 0 and signup_rate NULL.
  • Do not round.

Expected output

One row per campaign.

Column Type Description
campaign_id BIGINT
click_rate DOUBLE NULL if it cannot be computed.
signup_rate DOUBLE NULL if it cannot be computed.

Solve it in the browser

This editor runs DuckDB inside your browser. Nothing is installed and nothing is sent to a server. DuckDB's SQL is close to Spark SQL but not identical. DuckDB does not stop on a division by zero the way Spark 4 does. Guard the division anyway, so the same query works on both. The Colab notebook runs real Spark.

query.sql DuckDB, in your browser
Ctrl + Enter runs the query

Your result appears here. Your draft is kept in this browser.

Explanation

Show explanationGives the answer away. Try the problem first.

The approach

clicks / NULLIF(impressions, 0) AS click_rate

NULLIF(a, b) returns NULL when a equals b, and a otherwise. So a zero denominator becomes NULL, and dividing by NULL gives NULL. No error, and no invented number.

Nothing more is needed for the missing counts. Any arithmetic with a NULL in it is NULL, so a NULL clicks gives a NULL click_rate, and a NULL clicks in the denominator gives a NULL signup_rate.

The requirement separates two things that a report tends to merge:

  • 0 means it was measured and nothing happened: 2,000 impressions, 0 clicks.
  • NULL means there is nothing to measure, or the measurement is missing.

Of the 60 campaigns, click_rate is NULL for 10 (6 were never shown, 4 have no click count) and it is a real 0 for 5. signup_rate is NULL for 20.

In Spark / between two integers gives a DOUBLE, so no cast is needed. That is not true in every database: in some, 3 / 4 is 0.

Common wrong answers

Plain division: clicks / impressions. In Spark 4 the query stops:

[DIVIDE_BY_ZERO] Division by zero. Use `try_divide` to tolerate divisor being 0
and return NULL instead.

One campaign with zero impressions fails the whole report. Before Spark 4 the same query returned NULL for that row without saying anything, which is why old jobs break after an upgrade. DuckDB, in the browser editor, does neither: it returns inf for 1/0 and nan for 0/0, and carries on.

COALESCE(rate, 0). Removes the error and the meaning with it. A campaign that was never shown now has a click rate of 0, the same as one that was shown 2,000 times and ignored. Wrong for 20 of the 60 campaigns. Sorted by rate, the campaigns with broken tracking sit at the bottom with the genuinely bad ones.

CASE WHEN impressions = 0 THEN 0 ELSE clicks / impressions END. The same idea written out. Wrong for 11 campaigns.

COALESCE(clicks, 0) / NULLIF(impressions, 0). Replaces a missing count with 0 before dividing. "We do not know how many clicks there were" becomes "there were no clicks". Wrong for 9 campaigns.

ROUND(..., 4). The requirement says not to round. Rounding belongs where the number is displayed. A rounded rate that is later multiplied or averaged carries the rounding error along.

clicks DIV impressions. DIV is integer division: it returns a BIGINT, and every rate below 1 becomes 0.

Other ways to write it

Both give the same result as the reference solution:

CASE WHEN impressions > 0 THEN clicks / impressions END
try_divide(clicks, impressions)

try_divide is Spark only; it does not exist in DuckDB, so it does not run in the browser editor. NULLIF works everywhere.

A note on PySpark

The DataFrame version has the same choice to make:

F.col("clicks") / F.when(F.col("impressions") != 0, F.col("impressions"))

when without otherwise returns NULL, so this is NULLIF written in Python. F.try_divide("clicks", "impressions") also works.

Edge cases in the data

Case Campaigns Expected
Never shown: 0 impressions, 0 clicks, 0 signups 4 Both rates NULL.
Never shown, counts missing 2 Both rates NULL.
Shown, never clicked 5 click_rate 0, signup_rate NULL.
Shown, click count missing 4 Both rates NULL, even though signups were recorded.
Clicked, signup count missing 5 click_rate is a number, signup_rate NULL.