Learn SQL/Intermediate/Numeric Functions/SQL Avoid Division by Zero

SQL Avoid Division by Zero

Dividing by zero raises a genuine error in Postgres, not a NULL or an infinity — this closing lesson covers the standard guard using NULLIF.

What & Why

Unlike some languages, Postgres genuinely errors on division by zero — the query fails outright rather than returning a special "infinity" value. Any percentage or ratio calculation whose denominator could legitimately be zero needs a guard, and NULLIF (from the NULL Handling series) is the standard tool: convert a zero denominator into NULL first, since dividing by NULL safely returns NULL instead of erroring.

See How It Works

BUSINESS QUESTION

Marketing wants to compare the failure an unguarded bounce-rate calculation would cause with the safe NULLIF result.

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
Compare unguarded division with the NULLIF resultExample 1 of 4
unguarded bounces / recipients · guarded bounces / NULLIF(recipients, 0)
idrecipientsbouncesunguarded_behaviorguarded_bounce_rate_pct
2011200242.002.00
20280012??
203150031??
20400??

With 1,200 recipients, the unguarded and guarded calculations agree at 2.00 percent.

EXAMPLE QUERY
SELECT
  id,
  recipients,
  bounces,
  ROUND(bounces::numeric / NULLIF(recipients, 0) * 100, 2) AS guarded_bounce_rate_pct
FROM marketing.email_sends
ORDER BY id;
Now You Try

Practice this concept

Marketing wants an executable bounce-rate query even when an email send has zero recipients.

Available schema
marketing

Prefix tables with marketing.table_name.

idrecipientsbouncesguarded_bounce_rate_pct
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