NULL Functions

Replacing NULL

These functions return a substitute value when an expression is NULL:

FunctionDatabaseMeaning
COALESCE(a, b, c, ...)all (standard)first non-NULL argument
IFNULL(a, b)MySQL, SQLiteb if a is NULL
ISNULL(a, b)SQL Serverb if a is NULL
NVL(a, b)Oracleb 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

CustomerNameCity
Blue Harbor FoodsLondon
Golden SpoonUnknown
Harbor LightsLondon

Example (calculation)

Treat a missing stock as 0 in a calculation:

SELECT ProductName, Price * COALESCE(Stock, 0) AS StockValue
FROM Products;

Result: 6 rows

ProductNameStockValue
Basmati Rice 5kg1500
Green Tea 100 bags2025
Olive Oil 1L799.2
Dark Chocolate0
Espresso Beans 1kg810
Almonds 500g0

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

ProductNamePriceStockPricePerUnitInStock
Basmati Rice 5kg12.51200.1042
Green Tea 100 bags6.753000.0225
Olive Oil 1L9.99800.1249
Dark Chocolate3.490NULL
Espresso Beans 1kg18450
Almonds 500g8.25NULLNULL