COALESCE
is a SQL function that returns to the parameter listThe first non-NULL value. It is often used to deal with possible existenceNULL
A scene with a value and provides a default or alternate value.
grammar
COALESCE(expression1, expression2, ..., expressionN)
-
expression1, expression2, ..., expressionN
: A set of expressions evaluated in order from left to right. - The function returns the first non-NULL value if all expressions are
NULL
, then returnNULL
。
Common uses
-
Replace NULL value: Replace the default value with possible
NULL
field value. -
Multiple column priority: Select the highest priority and non-select from multiple columns
NULL
value. -
Simplify nesting logic: Replace complex
CASE
Expressions.
Example
1. Replace NULL value
In queryNULL
Replace with the specified default value.
SELECT COALESCE(NULL, 'Default Value') AS result;
result:
result |
---|
Default Value |
2. Used for field default values
Suppose there is a tableEmployees
, including the salary of employees (salary
) List. If the salary value isNULL
, the default display is0
。
SELECT employee_id, COALESCE(salary, 0) AS salary_with_default FROM Employees;
Sample data:
employee_id | salary |
---|---|
1 | 5000 |
2 | NULL |
result:
employee_id | salary_with_default |
---|---|
1 | 5000 |
2 | 0 |
3. Multiple column priority
Select the first non-NULL value from multiple columns, for example, preferentially display emails in contact information, followed by phone numbers.
SELECT COALESCE(email, phone, 'No Contact') AS contact_info FROM Customers;
Sample data:
phone | |
---|---|
john@ | NULL |
NULL | 1234567890 |
NULL | NULL |
result:
contact_info |
---|
john@ |
1234567890 |
No Contact |
4. Combining the aggregation function
During the calculation process, the processing may beNULL
value. For example, calculate the average value in a table, butNULL
The value uses the default value of 0.
SELECT AVG(COALESCE(score, 0)) AS avg_score FROM Tests;
Things to note
-
Data type consistency:
- All parameters must be of the same or compatible data type.
- If the parameter data types are inconsistent, the database will attempt to convert implicitly.
-
performance:
-
COALESCE
Performance may be slightly affected when the parameter list is long.
-
- and
IFNULL
Comparison:- Provided by MySQL
IFNULL(expression, value)
Functional similar toCOALESCE
, but only two parameters are supported.
- Provided by MySQL
Summarize
COALESCE
It is a powerful and commonly used SQL function, mainly used to handleNULL
Values and implement flexible value selection strategies can make query logic clearer and more concise.
This is all about this article about COALESCE function in MySQL. For more related content of mysql coalesce function, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!