Learn SQL/Intermediate/NULL Handling/SQL NULLIF (NULL Handling)

SQL NULLIF (NULL Handling)

The reverse of COALESCE — turns a specific value INTO NULL, most commonly used to guard against division by zero.

What & Why

NULLIF(a, b) returns NULL if a equals b, otherwise returns a unchanged. The single most common use: preventing a division-by-zero error by converting a zero denominator into NULL first — since dividing by NULL gives NULL, not an error.

See How It Works

BUSINESS QUESTION

Marketing wants click-through rate protected when a send has zero recipients.

idcampaign_idsent_atrecipientsopensclicksunsubscribesbounces
20112024-01-20 15:00:00+001200540180924
20222024-02-15 16:30:00+0080042096512
20332024-03-18 13:00:00+0015006102251431
20442024-04-08 14:00:00+0000000
EXAMPLE QUERY
SELECT
  id AS send_id,
  ROUND(100.0 * clicks / NULLIF(recipients, 0), 2) AS click_rate
FROM marketing.email_sends
ORDER BY send_id;
RESULT — exact output from the displayed Queryflo rows
send_idclick_rate
20115.00
20212.00
20315.00
204NULL

NULLIF turns Send 204's zero recipients into a safe NULL denominator.

Now You Try

Practice this concept

Marketing wants click-through rate protected when a send has zero recipients.

Available schema
marketing

Prefix tables with marketing.table_name.

send_idclick_rate
marketing.email_sends
ColumnType
idinteger
campaign_idinteger
sent_attimestamp with time zone
recipientsinteger
opensinteger
clicksinteger
unsubscribesinteger
bouncesinteger
legacy_send_grouptext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario