π§ͺ SQL NULL Functions β COALESCE, ISNULL, NULLIF Explained
π§² Introduction β Why Use NULL Functions?
In SQL, NULL
represents missing or unknown data. NULL functions help you manage, replace, and handle NULLs without breaking your logic or calculations.
π― In this guide, youβll learn:
- What common SQL NULL functions do
- Syntax and usage of
ISNULL()
,COALESCE()
, andNULLIF()
- Real-world examples for replacing NULLs and preventing divide-by-zero errors
β 1. IS NULL / IS NOT NULL (Test NULL Values)
SELECT * FROM users
WHERE email IS NULL;
β Filters rows where a column contains NULL.
WHERE age IS NOT NULL;
β Filters out rows with missing age values.
π 2. ISNULL() β SQL Server / MS Access
SELECT ISNULL(email, 'no-email@example.com') AS contact_email
FROM users;
β Replaces NULL with a default value.
π‘ Equivalent to IFNULL()
in MySQL.
π 3. COALESCE() β Standard SQL
SELECT COALESCE(phone, alternate_phone, 'N/A') AS contact_number
FROM customers;
β Returns the first non-NULL value in the list.
π Cross-platform and preferred for multiple fallback values.
π 4. NULLIF() β Return NULL When Two Values Are Equal
SELECT NULLIF(actual, expected) AS variance
FROM results;
β
Returns NULL
if actual = expected
; otherwise returns actual
.
π‘ Useful to prevent division by zero:
SELECT amount / NULLIF(quantity, 0) FROM inventory;
π§ 5. Common Use Cases
- Replace NULLs with readable labels
- Avoid divide-by-zero or error-prone calculations
- Provide fallback values in dashboards
- Normalize inconsistent or optional fields
π Best Practices
β Recommended | β Avoid This |
---|---|
Use COALESCE() for multiple fallbacks | Nesting ISNULL() when COALESCE() works better |
Test NULLs with IS NULL | Using = NULL or != NULL (invalid syntax) |
Use NULLIF() in divide-by-zero logic | Using CASE unnecessarily |
π Summary β Recap & Next Steps
NULL functions are essential tools for building resilient, readable SQL queries that handle incomplete or optional data smoothly.
π Key Takeaways:
ISNULL()
andIFNULL()
replace NULL with a default valueCOALESCE()
returns the first non-NULL in a listNULLIF()
avoids math errors by comparing values- Use
IS NULL
andIS NOT NULL
to filter properly
βοΈ Real-World Relevance:
Used in dashboards, financial calculations, data cleaning pipelines, and business rules.
β FAQ β SQL NULL Functions
β Whatβs the difference between ISNULL() and COALESCE()?
β
ISNULL()
works with two values; COALESCE()
can take many and is more portable.
β Does COALESCE() stop evaluating after a match?
β Yes. It returns the first non-NULL and skips the rest.
β Can I use NULLIF to avoid zero division?
β
Yes. Use NULLIF(quantity, 0)
in the denominator.
β Is ISNULL portable across databases?
β No. Use COALESCE()
for better cross-database compatibility.
β What happens if all COALESCE values are NULL?
β
The result is NULL
.
Share Now :