SQL NULL Function

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

See the 'Products' table below:

P_Id ProductName UnitPrice UnitsInStock UnitsOnOrder
1 computer 699 25 15
2 printer 365 36  
3 telephone 280 159 57

If 'UnitsOnOrder' is optional and can contain NULL values.

We use the following SELECT statement:

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

In de bovenstaande voorbeelden resulteert NULL waarde van "UnitsOnOrder" in NULL.

De ISNULL() functie van Microsoft wordt gebruikt om te bepalen hoe NULL-waarden moeten worden afgehandeld.

De NVL(), IFNULL() en COALESCE() functies kunnen ook hetzelfde resultaat bereiken.

Hier hopen we dat de NULL-waarden 0 zijn.

Hieronder, als "UnitsOnOrder" NULL is, is dit ongunstig voor de berekening, dus als de waarde NULL is, retourneert ISNULL() 0.

SQL Server / MS Access

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

Oracle

Oracle heeft geen ISNULL() functie. Maar we kunnen de NVL() functie gebruiken om hetzelfde resultaat te bereiken:

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

MySQL

MySQL heeft ook een soortgelijke ISNULL() functie. Maar het werkt iets anders dan de ISNULL() functie van Microsoft.

In MySQL kunnen we de IFNULL() functie gebruiken, zoals hieronder:

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

Of we kunnen de COALESCE() functie gebruiken, zoals hieronder:

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