The COALESCE function returns the specified non-null value, or the specified default value if all values are NULL. Usage: 1. Get the first non-null value; 2. Provide a default value; 3. Check multiple values in cascade. Note: Only the first non-null value is returned to ensure that the default value type is consistent. This function avoids NULL values in the query, ensuring that meaningful values are returned.
Usage of COALESCE function in SQL
COALESCE function is used to return the specified non- NULL, returns the specified default value if all values are NULL. The syntax is as follows:
<code class="sql">COALESCE(value1, value2, ..., valueN, default_value)</code>
Among them:
value1
, value2
,..., valueN
is Multiple values to check. default_value
is the default value to be returned if all values are NULL. Usage:
The COALESCE function is used to avoid NULL values in queries, especially in scenarios where it is necessary to ensure that non-null values are returned. Here are some usage examples:
<code class="sql">SELECT COALESCE(name, email) FROM users;</code>
The above query will return the user's name if there is no name , the email is returned.
<code class="sql">SELECT COALESCE(address, 'Unknown') FROM customers;</code>
The above query will return the customer's address, or if there is no address, the default value "Unknown" will be returned.
<code class="sql">SELECT COALESCE(first_name, last_name, username) FROM users;</code>
The above query will return the user's last name, first name, or username, checking these values in order , until a non-null value is found.
Note:
default_value
is of the same data type as the value being checked. The above is the detailed content of Usage of coalesce in sql. For more information, please follow other related articles on the PHP Chinese website!