SQL NULL
Functions
SQL ISNULL(), NVL(), IFNULL(), and COALESCE() Functions
Consider the "Products" table below:
P_Id | ProductName | UnitPrice | UnitsInStock | UnitsOnOrder |
---|---|---|---|---|
1 | Jarlsberg | 10.45 | 16 | 15 |
2 | Mascarpone | 32.56 | 23 | |
3 | Gorgonzola | 15.67 | 9 | 20 |
If "UnitsOnOrder" is optional and can contain NULL values.
We use the following SELECT statement:
In the example above, if "UnitsOnOrder" has a NULL value, the result is NULL.
Microsoft's ISNULL() function is used to specify how to handle NULL values.
The NVL(), IFNULL(), and COALESCE() functions can also achieve the same result.
Here, we want NULL values to be 0.
Below, if "UnitsOnOrder" is NULL, it will not affect the calculation because ISNULL() returns 0 if the value is NULL:
SQL Server / MS Access
Oracle
Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the same result:
MySQL
MySQL also has a function similar to ISNULL(). However, it works slightly differently from Microsoft's ISNULL() function.
In MySQL, we can use the IFNULL() function as follows:
Or we can use the COALESCE() function as follows: