MariaDB IFNULL() Function
The MariaDB IFNULL() function is used to provide alternate value if an expression is NULL. This function returns the expression, if the expression is NOT NULL.
Syntax
IFNULL(expression, value_if_null)
Parameters
expression |
Required. Specify the value to test as NULL. |
value_if_null |
Required. Specify the value to return if expression is NULL. |
Return Value
Returns expression, if expression is NOT NULL. Returns value_if_null, if expression is NULL.
Example 1:
The example below shows the usage of IFNULL() function.
SELECT IFNULL('Paris', 'London'); Result: 'Paris' SELECT IFNULL(NULL, 'London'); Result: 'London' SELECT IFNULL(5/0, 'Dividing by 0 returns NULL'); Result: 'Dividing by 0 returns NULL' SELECT IFNULL(DATE('2018-10-15'), '2018-10-31'); Result: '2018-10-15' SELECT IFNULL(DATE(NULL), '2018-10-31'); Result: '2018-10-31'
Example 2:
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 IFNULL() function is used which provides alternative value to the column if it contains NULL value.
SELECT *, Price * (StockQuantity + IFNULL(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 |
❮ MariaDB Functions