MySQL IFNULL()
The IFNULL()
function returns a specified value if the expression is NULL
. If the expression is not NULL
, it returns the expression itself. It is useful for handling NULL values in data.
Examples
1. Using IFNULL with a Column
SELECT king_name, IFNULL(reign_period, 'Unknown') AS period_description FROM tamil_kings_auto_increment;
Code Explanation: This query returns 'Unknown' if reign_period
is NULL
, otherwise it returns the actual reign_period
.
2. Using IFNULL with a Calculation
SELECT king_name, IFNULL(reign_years, 0) AS years_of_reign FROM tamil_kings_auto_increment;
Code Explanation: This query returns 0 if reign_years
is NULL
, otherwise it returns the actual value.
Best Practices
- Use
IFNULL()
to handle NULL values gracefully and avoid issues in calculations or displays. - Specify a meaningful default value when handling NULLs.
Key Takeaways
- The
IFNULL()
function replaces NULL values with a specified default value. - It is useful for ensuring data consistency and readability.