SQL NULLIF Function: Clean Empty Strings and Prevent Division by Zero
By Sharon Ben-Moshe · October 5, 2026 · 1 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.
Deep dive into SQL NULLIF(a, b). Learn how to convert empty strings to NULL, safeguard mathematical formulas, and pair NULLIF with COALESCE.
Quick answer
The SQL NULLIF(expression1, expression2) function compares two expressions. If expression1 equals expression2, it returns NULL; otherwise, it returns expression1. It is the ANSI SQL shorthand for CASE WHEN expression1 = expression2 THEN NULL ELSE expression1 END, making it ideal for converting blank strings ('') to NULL and preventing division by zero.
FAQs
What does NULLIF return if the expressions do not match?
It returns the first argument unchanged. For example, `NULLIF('Active', '')` returns `'Active'`.
How does NULLIF differ from COALESCE?
COALESCE takes multiple arguments and returns the first non-NULL value. NULLIF takes exactly two arguments and converts matching values into NULL. They are complementary: NULLIF produces NULLs, and COALESCE replaces NULLs.
Can NULLIF convert blank strings to NULL for database normalization?
Yes! Running `NULLIF(TRIM(input_text), '')` converts empty or whitespace-only strings into SQL NULL, enforcing clean database hygiene.
Is NULLIF supported in all SQL dialects?
Yes, NULLIF is part of the core ANSI SQL standard and is supported identically across PostgreSQL, MySQL, SQL Server, SQLite, and BigQuery.
Keep reading
The Comprehensive Guide to SQL Data Types: Storage, Precision, and Cross-Dialect Portability
By Sharon Ben-Moshe · Oct 13, 2026
The complete guide to SQL data types across PostgreSQL, MySQL, SQL Server, and SQLite. Numeric precision, character sets, timestamps, and JSON.
Read postThe Definitive Guide to SQL Window Functions: Syntax, Framing, and Real-World Recipes
By Sharon Ben-Moshe · Oct 13, 2026
The comprehensive guide to SQL window functions. Master OVER, PARTITION BY, ORDER BY, window frames (ROWS vs RANGE), and ranking recipes.
Read postTry it now
Paste your SQL into sqlfmt — format, validate, and catch typos free in your browser.