SQL Server - ISNULL() Function
The NULL function can be used to provided alternate value of a column if it contains NULL value. In SQL Server (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:
ProductName | Price | StockQuantity | OrderQuantity |
---|---|---|---|
Apple | 1.00 | 100 | 20 |
Banana | 1.25 | 120 | 30 |
Orange | 2.15 | 105 | NULL |
Watermelon | 3.50 | 75 | 15 |
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:
ProductName | Price | StockQuantity | OrderQuantity | Inventory |
---|---|---|---|---|
Apple | 1.00 | 100 | 20 | 120.0 |
Banana | 1.25 | 120 | 30 | 187.5 |
Orange | 2.15 | 105 | NULL | NULL |
Watermelon | 3.50 | 75 | 15 | 315.0 |
To avoid such situations, the NULL function is used which provides alternative value to a column if it contains NULL value.
SQL Server (Transact-SQL) ISNULL() Function
The SQL Server (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:
ProductName | Price | StockQuantity | OrderQuantity | Inventory |
---|---|---|---|---|
Apple | 1.00 | 100 | 20 | 120.0 |
Banana | 1.25 | 120 | 30 | 187.5 |
Orange | 2.15 | 105 | NULL | 225.75 |
Watermelon | 3.50 | 75 | 15 | 315.0 |