IFNULL function is used to check whether the expression is NULL, if so, it returns the specified default value, otherwise it returns the value of the expression. It prevents null values from causing errors, allows manipulation of null values, and improves the readability of queries. Usage includes: replacing null values with default values, excluding null values from calculations, and nested usage to handle multiple null value situations.
Usage of IFNULL in SQL
The IFNULL function is used to check whether the expression is NULL. If it is NULL, Returns the specified default value; if not NULL, returns the value of the expression.
Syntax:
<code class="sql">IFNULL(expression, default_value)</code>
Where:
expression
: The expression to be checked. default_value
: The value to be returned if expression
is NULL. Usage:
The IFNULL function is mainly used to replace null values with specified default values. For example, the following query uses IFNULL to replace null values in the name
column with the string "Unnamed":
<code class="sql">SELECT IFNULL(name, '无名') AS name FROM table_name;</code>
Advantages:
Note:
default_value
can be any data type. expression
and default_value
do not match, the SQL engine will automatically perform an implicit conversion. Example:
Replace null values in the age
column with 0:
<code class="sql">SELECT IFNULL(age, 0) AS age FROM table_name;</code>
Exclude null values in the COUNT()
function:
<code class="sql">SELECT COUNT(IFNULL(name, '')) AS num_names FROM table_name;</code>
Use the nested IFNULL function to handle multiple null values:
<code class="sql">SELECT IFNULL(name, IFNULL(nickname, '无名')) AS name FROM table_name;</code>
The above is the detailed content of Usage of ifnull in sql. For more information, please follow other related articles on the PHP Chinese website!