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:

  1. expr1: To check if a field or expression is NULL.
  2. expr2: Returns the value if expr1 is NULL.

Suppose there is a table called students, which includes the fields: id, name, age.

  1. Return the age field, and if age is NULL, return 0:
    SELECT COALESCE(age, 0) FROM students;
  2. Retrieve the name field, and if the name is NULL, return ‘Unknown’:
    SELECT COALESCE(name, ‘Unknown’) FROM students;

Notice:

  1. The IFNULL function only accepts two parameters and cannot have more than two.
  2. The first parameter can be a field name, expression, or constant, but the second parameter must be a constant.
广告
Closing in 10 seconds
bannerAds