How to use the SQL COALESCE function?

The COALESCE function is used to return the first non-NULL value in a list of parameters. Its syntax is as follows:

COALESCE(expr1, expr2, ...)

expr1, expr2, etc. represent the list of parameters to be evaluated, which can include any number of parameters.

Example of use:

Assuming there is a table named orders with columns id, date, and status. Now we need to query the status of orders, and if the status is empty, return “Unknown status”.

SELECT id, COALESCE(status, '未知状态') AS status
FROM orders;

In the above example, the COALESCE function will return “Unknown status” as the result if the value of the status column is NULL. If the value of the status column is not NULL, it will return the actual status value.

bannerAds