How to Fix Division by Zero in SQL: NULLIF and Safe Division
By Sharon Ben-Moshe · September 2, 2026 · 2 min read
Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Learn how to prevent and fix division by zero errors in SQL using NULLIF, CASE expressions, and database-specific safe division functions.
Quick answer
The most standard and concise way to prevent a division by zero error in SQL is wrapping the divisor in NULLIF(divisor, 0). Because any number divided by NULL yields NULL instead of throwing an error, this eliminates query crashes in PostgreSQL, SQL Server, and SQLite without verbose CASE statements.
FAQs
Why does SQL throw an error on division by zero?
In relational algebra and mathematics, division by zero is undefined. Rather than assuming zero or infinity, most SQL engines (like PostgreSQL 22012 and SQL Server Msg 8134) abort the transaction to avoid silent data corruption unless explicitly handled.
How does NULLIF prevent division by zero?
NULLIF(x, y) returns NULL if x equals y, and x otherwise. When you write `numerator / NULLIF(denominator, 0)`, a zero denominator becomes NULL. In SQL arithmetic, `val / NULL` evaluates safely to NULL instead of an exception.
How do I return 0 instead of NULL when the divisor is zero?
Wrap the entire division expression with COALESCE: `COALESCE(numerator / NULLIF(denominator, 0), 0)`. If the division returns NULL because the divisor was 0 or NULL, COALESCE substitutes your fallback value 0.
Does Google BigQuery throw division by zero errors?
Standard division `/` in BigQuery throws an error on zero. However, BigQuery provides the built-in SAFE_DIVIDE(X, Y) function, which automatically returns NULL instead of raising an error if Y is zero.
Keep reading
Fix BigQuery "Unrecognized Name" Error: Scoping and Syntax Rules
By Sharon Ben-Moshe · Sep 29, 2026
Fix Google BigQuery's "Unrecognized name: column" error. Learn alias visibility rules across WHERE and QUALIFY, case sensitivity, and struct unnesting.
Read postSQLite "Datatype Mismatch" (Error 20): Type Affinity and Strict Tables
By Sharon Ben-Moshe · Sep 26, 2026
Understand SQLite Error 20 (datatype mismatch). Learn how SQLite type affinity, CHECK constraints, and STRICT tables enforce data integrity.
Read postTry it now
Paste your SQL into sqlfmt — format, validate, and catch typos free in your browser.