SQL NULL- functies
SQL IFNULL(), ISNULL(), COALESCE() en NVL()-functies
Bekijk de volgende tabel "Producten":
P_Id | ProductName | UnitPrice | UnitsInStock | UnitsOnOrder |
---|---|---|---|---|
1 | Jarlsberg | 10.45 | 16 | 15 |
2 | Mascarpone | 32.56 | 23 | |
3 | Gorgonzola | 15.67 | 9 | 20 |
Stel dat de kolom "UnitsOnOrder" optioneel is en NULL-waarden kan bevatten.
Bekijk de volgende SELECT-instructie:
SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)
FROM Products;
Als in het bovenstaande voorbeeld een van de "UnitsOnOrder"-waarden NULL is, is het resultaat NULL.
Oplossingen
MySQL
Met de MySQL- IFNULL()
functie kunt u een alternatieve waarde retourneren als een expressie NULL is:
SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))
FROM Products;
of we kunnen de functie gebruiken, zoals deze:
COALESCE()
SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))
FROM Products;
SQL-server
Met de SQL Server-
ISNULL()
functie kunt u een alternatieve waarde retourneren wanneer een expressie NULL is:
SELECT ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder, 0))
FROM Products;
MS-Access
De MS Access-
IsNull()
functie retourneert TRUE (-1) als de expressie een null-waarde is, anders ONWAAR (0):
SELECT ProductName, UnitPrice * (UnitsInStock + IIF(IsNull(UnitsOnOrder), 0, UnitsOnOrder))
FROM Products;
Orakel
De Oracle- NVL()
functie bereikt hetzelfde resultaat:
SELECT ProductName, UnitPrice * (UnitsInStock + NVL(UnitsOnOrder, 0))
FROM Products;