SQL NULLIF

The mirror image of COALESCE — turns a specific value INTO NULL, most often to guard against a division by zero.

What & Why

NULLIF(value1, value2) compares its two arguments: if they're equal, it returns NULL; otherwise, it returns value1 unchanged. Where COALESCE replaces a NULL with something else, NULLIF does the opposite — it deliberately turns a specific real value into a NULL.

The single most common use is guarding a division against a zero denominator. Dividing by zero raises an error in Postgres — but dividing by NULL just produces NULL as the result, which is usually a far more graceful way to handle it in a report.

See How It Works

BUSINESS QUESTION

Marketing wants click rates for every email send without a zero-recipient send crashing the report.

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
Watch NULLIF neutralize a matching valueExample 1 of 4
clicks::numeric / NULLIF(recipients, 0)
idclicksrecipientsclick_rate
20118012000.1500
20296800?
2032251500?
20400?

Recipients is non-zero, so NULLIF returns 1200 and division succeeds.

EXAMPLE QUERY
SELECT
  id AS send_id,
  clicks,
  recipients,
  clicks::numeric / NULLIF(recipients, 0) AS click_rate
FROM marketing.email_sends
ORDER BY send_id
LIMIT 20;
Now You Try

Practice this concept

Marketing wants click rates for every email send without a zero-recipient send crashing the report.

Available schema
marketing

Prefix tables with marketing.table_name.

send_idclicksrecipientsclick_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