sql_isnull
SQL NULL Value Handling: COALESCE, ISNULL, NVL, IFNULL
Section titled “SQL NULL Value Handling: COALESCE, ISNULL, NVL, IFNULL”The Challenge of NULL Values in Calculations
Section titled “The Challenge of NULL Values in Calculations”In SQL, NULL represents a missing, unknown, or inapplicable value. A common challenge arises when NULL values are involved in arithmetic operations or string concatenations, as they typically propagate, resulting in NULL for the entire expression. This section explores standard and DBMS-specific functions to gracefully handle NULLs by substituting them with a default value.
Illustrative Scenario: Product Inventory Calculation
Consider a Products table where UnitsOnOrder might be NULL if no units are currently on order:
ProductID | ProductName | UnitPrice | UnitsInStock | UnitsOnOrder----------|-------------|-----------|--------------|--------------1 | Jarlsberg | 10.45 | 16 | 152 | Mascarpone | 32.56 | 23 | NULL3 | Gorgonzola | 15.67 | 9 | 204 | Mozzarella | 12.00 | 30 | NULLIf we try to calculate the total potential stock value like this:
SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder) AS PotentialValueFROM Products;For products where UnitsOnOrder is NULL (like Mascarpone and Mozzarella), the PotentialValue will also be NULL because any_number + NULL results in NULL.
Solutions for Handling NULLs
Section titled “Solutions for Handling NULLs”To address this, SQL provides several functions. The most standard and portable is COALESCE().
1. COALESCE(expression1, expression2, ..., default_value) (SQL Standard)
Section titled “1. COALESCE(expression1, expression2, ..., default_value) (SQL Standard)”COALESCE() returns the first non-NULL expression in its argument list. It’s the preferred method due to its standardization and flexibility.
SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0)) AS PotentialValueFROM Products;In this query, if UnitsOnOrder is NULL, COALESCE(UnitsOnOrder, 0) will return 0, allowing the calculation to proceed correctly.
Why COALESCE is Generally Preferred:
Section titled “Why COALESCE is Generally Preferred:”- SQL Standard: Ensures better portability across different database systems.
- Flexibility: Can accept multiple arguments, returning the first one that is not
NULL. For example,COALESCE(optional_discount, default_discount, 0).
2. DBMS-Specific Functions (Use with Awareness of Portability)
Section titled “2. DBMS-Specific Functions (Use with Awareness of Portability)”While COALESCE is standard, various DBMS offer their own functions for NULL replacement, often with slightly different behavior or syntax:
SQL Server: ISNULL(check_expression, replacement_value)
Section titled “SQL Server: ISNULL(check_expression, replacement_value)”ISNULL() replaces NULL with the specified replacement_value. It only takes two arguments. The data type of the result is determined by the check_expression.
SELECT ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder, 0)) AS PotentialValueFROM Products; -- For SQL ServerOracle: NVL(expression1, expression2)
Section titled “Oracle: NVL(expression1, expression2)”NVL() checks if expression1 is NULL. If so, it returns expression2; otherwise, it returns expression1. Data types must be compatible or implicitly convertible.
SELECT ProductName, UnitPrice * (UnitsInStock + NVL(UnitsOnOrder, 0)) AS PotentialValueFROM Products; -- For OracleOracle also has NVL2(expression1, value_if_not_null, value_if_null) and COALESCE.
MySQL: IFNULL(expression1, expression2)
Section titled “MySQL: IFNULL(expression1, expression2)”IFNULL() returns expression2 if expression1 is NULL; otherwise, it returns expression1.
SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0)) AS PotentialValueFROM Products; -- For MySQLMySQL also has ISNULL(expression), but it works differently: it returns 1 (true) if expression is NULL, and 0 (false) otherwise. It’s a test, not a replacement function. Therefore, IFNULL or COALESCE are used for replacement in MySQL.
MS Access: Nz(variant, valueifnull)
Section titled “MS Access: Nz(variant, valueifnull)”The Nz() (Null Zero) function returns zero, a zero-length string (""), or another specified value when a Variant is NULL.
SELECT ProductName, UnitPrice * (UnitsInStock + Nz(UnitsOnOrder, 0)) AS PotentialValueFROM Products; -- For MS Access queriesMS Access also generally supports COALESCE in modern versions via ODBC/OLE DB connections to more capable database engines.
Summary of Recommendations
Section titled “Summary of Recommendations”- Prioritize
COALESCE(): For new development, useCOALESCE()forNULLvalue replacement to ensure better code portability and adherence to SQL standards. - Understand DBMS specifics: If working with existing codebases or specific DBMS features are needed, be aware of functions like
ISNULL(),NVL(), andIFNULL(), but understand their limitations regarding portability. - Test NULL conditions: Always consider how
NULLvalues might affect your queries and include explicit handling where necessary to prevent unexpectedNULLresults or errors.
Handling NULL in WHERE clauses: Remember that WHERE column_name = NULL or WHERE column_name != NULL usually don’t work as expected. Use WHERE column_name IS NULL or WHERE column_name IS NOT NULL instead.