📜  ifnull postgres - SQL (1)

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

IFNULL in PostgreSQL

In PostgreSQL, the IFNULL function is not available. However, there is an equivalent function called COALESCE.

COALESCE

The COALESCE function returns the first non-null value in a list of arguments. The syntax for the function is as follows:

COALESCE(value1, value2, ..., valueN)
  • value1, value2,...,valueN are the values to check for null.

If all values are null, then the function returns null.

Example
SELECT COALESCE(NULL, 'hello', NULL, 'world', NULL);  -- Output: 'hello'
SELECT COALESCE(NULL, NULL, NULL);                    -- Output: NULL
Usage

The COALESCE function can be used in many ways, such as:

1. Selecting non-null values from a table

SELECT COALESCE(name, email, phone, 'N/A') AS contact
FROM users;

The above query will return a list of contacts from users table. If name, email, or phone is null, then N/A will be returned as the contact.

2. Updating a table with non-null values

UPDATE users
SET name = COALESCE(name, 'User'),
    email = COALESCE(email, 'user@example.com'),
    phone = COALESCE(phone, '000-000-0000');

The above query will update the users table with non-null values for name, email, and phone. If any of these values are null, then default values will be used.

Conclusion

In PostgreSQL, the IFNULL function is not available, but it has an equivalent function called COALESCE. It works in a similar way as IFNULL in other databases.