📜  PostgreSQL – COALESCE(1)

📅  最后修改于: 2023-12-03 15:03:49.253000             🧑  作者: Mango

PostgreSQL - COALESCE

COALESCE is a useful function in PostgreSQL that allows you to choose the first non-null value from a list of values. It takes two or more arguments and returns the first non-null value from them.

Syntax
COALESCE(value1, value2, ...)
Example

Suppose you have a table named employees that has columns named first_name, last_name, and nickname. Some employees have a nickname, while others do not.

| first_name | last_name | nickname |
|------------|-----------|----------|
| Alice      | Smith     |          |
| Bob        | Johnson   | Bob      |
| Cindy      | Lee       | Cindy    |

You can use COALESCE to return the first non-null value for each employee's name:

SELECT COALESCE(nickname, first_name, last_name) FROM employees;

This SQL statement will return:

| coalesce   |
|------------|
| Alice Smith|
| Bob        |
| Cindy      |

As you can see, for Alice Smith, COALESCE chooses the first_name and last_name values since the nickname is null. For Bob Johnson, it chooses the nickname value, and for Cindy Lee, it chooses the nickname value as well.

Conclusion

In conclusion, COALESCE is a useful function in PostgreSQL that allows you to choose the first non-null value from a list of values. It can help simplify your SQL statements and make them easier to read and understand.