How is the function of ifnull used in MySQL?
In MySQL, the IFNULL function is used to determine if a field is NULL. If it is NULL, a specified value is returned; if it is not NULL, the field’s original value is returned.
Syntax:
IFNULL(expr1, expr2) means if expr1 is null, then return expr2.
Explanation of Parameters:
- expr1: To check if a field or expression is NULL.
- expr2: Returns the value if expr1 is NULL.
Suppose there is a table called students, which includes the fields: id, name, age.
- Return the age field, and if age is NULL, return 0:
SELECT COALESCE(age, 0) FROM students; - Retrieve the name field, and if the name is NULL, return ‘Unknown’:
SELECT COALESCE(name, ‘Unknown’) FROM students;
Notice:
- The IFNULL function only accepts two parameters and cannot have more than two.
- The first parameter can be a field name, expression, or constant, but the second parameter must be a constant.