SQL NULL Functions: Using the methods and case analysis

SQL NULL Functions


SQL ISNULL (), NVL (), IFNULL () and COALESCE () function

Look at the following "Products" table:

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 may contain a NULL value.

We use the following SELECT statement:

SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)
FROM Products

In the example above, if there is "UnitsOnOrder" value is NULL, then the result is NULL.

Microsoft's ISNULL () function is used to specify how to handle NULL values.

NVL (), IFNULL () and the COALESCE () function can also achieve the same result.

Here, we want NULL value is zero.

Hereinafter, if "UnitsOnOrder" is NULL, it will not affect the calculation, if the value is NULL because then the ISNULL () returns 0:

SQL Server / MS Access

SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))
FROM Products

Oracle

Oracle did not ISNULL () function. However, we can use the NVL () function to achieve the same results:

SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))
FROM Products

MySQL

MySQL also has a similar ISNULL () function. But it works with Microsoft's ISNULL () function is a bit different.

In MySQL, we can use the IFNULL () function, as follows:

SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))
FROM Products

Alternatively we can use the COALESCE () function, as follows:

SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))
FROM Products

Guess you like

Origin www.cnblogs.com/peijz/p/12501762.html