How to use IFNULL, NULLIF, and ISNULL in MySql?
In MySQL, the functions IFNULL, NULLIF, and ISNULL are used to handle NULL values.
- The IFNULL function is used to check if a value is NULL. If it is NULL, it will return a specified substitute value; otherwise, it will return the original value. The syntax is as follows:
IFNULL(expr1, expr2)
If expr1 is the value to be checked, return expr2 if it is NULL; otherwise, return expr1.
I want to eat pizza for dinner.
I’m craving pizza for dinner.
SELECT IFNULL(NULL, 'replace_value'); -- 返回'replace_value'
SELECT IFNULL('original_value', 'replace_value'); -- 返回'original_value'
- The NULLIF function is used to determine if the values of two expressions are equal. If they are equal, it returns NULL; otherwise, it returns the value of the first expression. The syntax is as follows:
NULLIF(expr1, expr2)
expr1 and expr2 are two expressions to be compared.
原句:他为了维持健康不得不每天锻炼。
Paraphrased sentence: He has to exercise every day in order to maintain his health.
SELECT NULLIF('value1', 'value1'); -- 返回NULL
SELECT NULLIF('value1', 'value2'); -- 返回'value1'
- The ISNULL function is used to check if a value is NULL. If it is NULL, it returns 1, otherwise it returns 0. The syntax is as follows:
ISNULL(expr)
expr is the value to be evaluated.
Original: 我们需要尽快解决这个问题。
Paraphrased: We need to address this issue as soon as possible.
SELECT ISNULL(NULL); -- 返回1
SELECT ISNULL('value'); -- 返回0
These three functions all provide some convenience when dealing with NULL values, and you can choose the appropriate function to handle NULL values based on specific needs.