IFERROR in SQL

IFERROR returns a fallback value when a formula produces an error such as a division by zero; in SQL you prevent the error with NULLIF and supply a default with COALESCE.

The Excel version

=IFERROR(B2/C2, 0)

The SQL equivalent

This example assumes: campaign_stats(id bigint, spend numeric, clicks numeric). It is written in PostgreSQL syntax, and your table and column names will differ from these.

SELECT id,
       COALESCE(spend / NULLIF(clicks, 0), 0) AS cost_per_click
FROM campaign_stats
ORDER BY id;

How it works

  • NULLIF(clicks, 0) turns a zero divisor into null, so the division returns null instead of failing.
  • COALESCE(..., 0) replaces that null with the fallback, like the second argument of IFERROR.
  • Handling the cause (a zero divisor) is safer than catching every possible error.

Where the results differ from Excel

  • In SQL a division by zero stops the whole query with an error, rather than showing an error in one cell, so it must be prevented.
  • IFERROR hides every kind of error, including typos; NULLIF only handles the case you intended.
  • Replacing a missing ratio with 0 can mislead; null (shown as blank) is often more honest for rates.

Skip the query: ask in plain English

If you would rather not write SQL, type the question. SchemaChat turns it into SQL against your connected database or uploaded file, runs it, and shows the SQL and the figures it used so you can check the answer before you share it. Check that the result matches how your spreadsheet defines the number.

  • Show cost per click for each campaign, leaving it blank when there were no clicks.
  • Which campaigns had spend but zero clicks?

Frequently asked questions

What is the SQL equivalent of IFERROR?
IFERROR returns a fallback value when a formula produces an error such as a division by zero; in SQL you prevent the error with NULLIF and supply a default with COALESCE.
How does the SQL version of IFERROR work?
NULLIF(clicks, 0) turns a zero divisor into null, so the division returns null instead of failing. COALESCE(..., 0) replaces that null with the fallback, like the second argument of IFERROR. Handling the cause (a zero divisor) is safer than catching every possible error.
Why can SQL give a different result from IFERROR?
In SQL a division by zero stops the whole query with an error, rather than showing an error in one cell, so it must be prevented.