Careeroza
NULL Functions
Replacing NULL
These functions return a substitute value when an expression is NULL:
| Function | Database | Meaning |
|---|---|---|
COALESCE(a, b, c, ...) | all (standard) | first non-NULL argument |
IFNULL(a, b) | MySQL, SQLite | b if a is NULL |
ISNULL(a, b) | SQL Server | b if a is NULL |
NVL(a, b) | Oracle | b if a is NULL |
NULLIF(a, b) | all (standard) | NULL if a = b, otherwise a |
Tip: Prefer COALESCE: it is standard SQL and accepts any number of arguments.
COALESCE
Example
Show "Unknown" for a missing city and 0 for missing stock:
SELECT CustomerName, COALESCE(City, 'Unknown') AS City
FROM Customers
WHERE Country IN ('Singapore', 'UK');Result: 3 rows
| CustomerName | City |
|---|---|
| Blue Harbor Foods | London |
| Golden Spoon | Unknown |
| Harbor Lights | London |
Example (calculation)
Treat a missing stock as 0 in a calculation:
SELECT ProductName, Price * COALESCE(Stock, 0) AS StockValue
FROM Products;Result: 6 rows
| ProductName | StockValue |
|---|---|
| Basmati Rice 5kg | 1500 |
| Green Tea 100 bags | 2025 |
| Olive Oil 1L | 799.2 |
| Dark Chocolate | 0 |
| Espresso Beans 1kg | 810 |
| Almonds 500g | 0 |
NULLIF
NULLIF is often used to avoid "division by zero" errors: dividing by NULL gives NULL instead of an error.
Example
Price per unit in stock, without a division-by-zero error for Dark Chocolate (stock 0):
SELECT ProductName, Price, Stock,
ROUND(Price / NULLIF(Stock, 0), 4) AS PricePerUnitInStock
FROM Products;Result: 6 rows
| ProductName | Price | Stock | PricePerUnitInStock |
|---|---|---|---|
| Basmati Rice 5kg | 12.5 | 120 | 0.1042 |
| Green Tea 100 bags | 6.75 | 300 | 0.0225 |
| Olive Oil 1L | 9.99 | 80 | 0.1249 |
| Dark Chocolate | 3.49 | 0 | NULL |
| Espresso Beans 1kg | 18 | 45 | 0 |
| Almonds 500g | 8.25 | NULL | NULL |