T-SQL Tutorial T-SQL Advanced Database Management T-SQL References

T-SQL - ISNULL() Function



The NULL function can be used to provided alternate value of a column if it contains NULL value. In T-SQL (Transact-SQL), ISNULL() function allows to return an alternative value when an expression is NULL.

Example:

Consider a database table called Product with the following records:

ProductNamePriceStockQuantityOrderQuantity
Apple1.0010020
Banana1.2512030
Orange2.15105NULL
Watermelon3.507515

If the OrderQuantity is optional and can contain NULL values. The statement mentioned below will give NULL value.

SELECT *, Price * (StockQuantity + OrderQuantity) AS Inventory
FROM Product;

This will produce the result as shown below:

ProductNamePriceStockQuantityOrderQuantityInventory
Apple1.0010020120.0
Banana1.2512030187.5
Orange2.15105NULLNULL
Watermelon3.507515315.0

To avoid such situations, the NULL function is used which provides alternative value to a column if it contains NULL value.

T-SQL (Transact-SQL) ISNULL() Function

The T-SQL (Transact-SQL) ISNULL() function lets you to provide an alternative value if column value is NULL. The statement below returns 0 if the value is NULL.

SELECT *, Price * (StockQuantity + ISNULL(OrderQuantity, 0)) AS Inventory
FROM Product;

This will produce the result as shown below:

ProductNamePriceStockQuantityOrderQuantityInventory
Apple1.0010020120.0
Banana1.2512030187.5
Orange2.15105NULL225.75
Watermelon3.507515315.0