How to use the ifnull function in MySQL?
The IFNULL() function in MySQL is used to check if a field is NULL, and if it is, it returns a specified value, otherwise it returns the field itself. The syntax is as follows:
IFNULL(expr1, expr2)
Among them, expr1 is the field or expression to be judged. If it is NULL, return expr2; otherwise, return expr1.
Here is an example of using the IFNULL() function:
Suppose there is a table called students, which includes the fields: id, name, and age. Now we want to query the names and ages of the students, and if the age is NULL, return the string “Unknown.”
SELECT name, IFNULL(age, 'Unknown') AS age
FROM students;
In this example, we use IFNULL(age, ‘Unknown’) to check if the age field is NULL. If it is, it will return the string “Unknown”; otherwise, it will return the age field itself. The final query result will include the student’s name and age.
I hope this is helpful for you!