SQL NULL Functions
Here is a clear and practical guide to the most important SQL NULL-handling functions, including examples for PostgreSQL, MySQL, SQL Server, and Oracle.
✅ Why NULL Functions Matter
In SQL, NULL means “unknown or missing value.”
Most expressions and comparisons return NULL when NULL is involved, so special functions exist to safely replace or handle NULLs.
🔹 1. COALESCE() (ANSI Standard — works in PostgreSQL, MySQL, SQL Server, Oracle)
Returns the first non-NULL value in the list.
✔ Most portable
✔ Most recommended
✔ Handles multiple arguments
🔹 2. ISNULL() (SQL Server only)
Equivalent to COALESCE() but only takes two arguments.
🔹 3. IFNULL() (MySQL only)
Same purpose as ISNULL() in SQL Server.
🔹 4. NVL() (Oracle only)
Oracle’s version of NULL replacement.
🔹 5. NULLIF() (ANSI Standard)
Returns NULL if the two expressions are equal, otherwise returns the first expression.
Useful to avoid division by zero:
🔥 Comparison: COALESCE vs IFNULL vs ISNULL vs NVL
| Function | DBMS | Args | Notes |
|---|---|---|---|
| COALESCE | All | Many | Most portable, best practice |
| IFNULL | MySQL | 2 | Fast, MySQL-specific |
| ISNULL | SQL Server | 2 | SQL Server-specific |
| NVL | Oracle | 2 | Oracle-specific |
| NULLIF | All | 2 | Converts equality to NULL |
📌 Practical Examples
Replace NULL salary with default
Default country when missing
Count only non-NULL values (using CASE)
Avoid division-by-zero with NULLIF
🧠 Best Practices
✔ Prefer COALESCE for cross-database code
✔ Use DB-specific functions only when needed
✔ Avoid storing empty strings instead of NULL
✔ Always handle NULL when doing math
✔ Use NULLIF to safely handle “invalid” values
