MySQL IFNULL() Function
The IFNULL() function in MySQL provides a way to handle potential NULL values in your data. It lets you specify a substitute value to use in place of NULL if a particular expression evaluates to NULL.
IFNULL(): Definition and Usage
NULL values can sometimes cause problems in queries or applications. IFNULL() allows you to replace NULL values with a value of your choosing, making your data more consistent and easier to work with. If the expression is not NULL, the function simply returns the expression's value.
Syntax
Syntax
IFNULL(expression, alt_value)
Parameter Values
| Parameter | Description |
|---|---|
expression |
The value or expression you want to check for NULL. This is required. |
alt_value |
The value to return if the expression is NULL. This is required. |
Examples
Handling a NULL Value
This example replaces a NULL value with "W3Schools.com".
Syntax
SELECT IFNULL(NULL, "W3Schools.com");
Output
W3Schools.com
Handling a Non-NULL Value
If the expression is not NULL, the expression's value is returned.
Syntax
SELECT IFNULL("Hello", "W3Schools.com");
Output
Hello
Replacing NULL with a Number
Replacing a NULL with a numeric value.
Syntax
SELECT IFNULL(NULL, 500);
Output
500