📜  nvl postgres - SQL (1)

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

NVL PostgreSQL - SQL

Introduction

In PostgreSQL, the NVL function is not available. However, you can achieve similar functionality by using the COALESCE function. COALESCE function returns the first non-null argument, or NULL if all arguments are NULL. This function is similar to the NVL function in Oracle.

Syntax

The syntax of the COALESCE function is:

COALESCE(expr1, expr2, ...., expr_n)

where expr1, expr2, …, expr_n are the expressions to be evaluated.

Examples
Example 1: Using COALESCE function

Suppose you have a table t1 with columns id, name, and age. Some values in the age column are NULL. You can use the COALESCE function to display the age of the person as 'NA' if the age is NULL.

SELECT id, name, COALESCE(age, 'NA') as age FROM t1;
Example 2: Combining COALESCE and CASE expressions

Suppose you have a table t1 with columns id, name, age, and salary. The salary column has some NULL values. In such cases, you can use the COALESCE and the CASE expressions together to display the salary as 'Not disclosed' if the salary is NULL.

SELECT id, name, age, 
CASE WHEN COALESCE(salary, -1) = -1 THEN 'Not disclosed' 
ELSE salary::text END as salary 
FROM t1;

In the above query, we first converted the salary column into text using the ::text operator. This is required because the CASE expression requires the same data type for all its expressions.

Conclusion

Although PostgreSQL does not have the NVL function, the COALESCE function can be used to achieve similar functionality. COALESCE function returns the first non-null argument, or NULL if all arguments are NULL. In this way, you can handle NULL values in your queries.