Fonctions SQL NULL
Fonctions SQL IFNULL(), ISNULL(), COALESCE() et NVL()
Regardez le tableau "Produits" suivant :
P_Id | ProductName | UnitPrice | UnitsInStock | UnitsOnOrder |
---|---|---|---|---|
1 | Jarlsberg | 10.45 | 16 | 15 |
2 | Mascarpone | 32.56 | 23 | |
3 | Gorgonzola | 15.67 | 9 | 20 |
Supposons que la colonne "UnitsOnOrder" est facultative et peut contenir des valeurs NULL.
Regardez l'instruction SELECT suivante :
SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)
FROM Products;
Dans l'exemple ci-dessus, si l'une des valeurs "UnitsOnOrder" est NULL, le résultat sera NULL.
Solutions
MySQL
La fonction MySQL IFNULL()
vous permet de renvoyer une valeur alternative si une expression est NULL :
SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))
FROM Products;
ou nous pouvons utiliser la fonction, comme ceci :
COALESCE()
SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))
FROM Products;
serveur SQL
La fonction SQL Server
ISNULL()
vous permet de renvoyer une valeur alternative lorsqu'une expression est NULL :
SELECT ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder, 0))
FROM Products;
MS Access
La fonction MS Access
IsNull()
renvoie TRUE (-1) si l'expression est une valeur nulle, sinon FALSE (0) :
SELECT ProductName, UnitPrice * (UnitsInStock + IIF(IsNull(UnitsOnOrder), 0, UnitsOnOrder))
FROM Products;
Oracle
La fonction Oracle NVL()
obtient le même résultat :
SELECT ProductName, UnitPrice * (UnitsInStock + NVL(UnitsOnOrder, 0))
FROM Products;