Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Friday, 16 February 2024

COALESCE in Greenplum

In Greenplum Database, the COALESCE function is used to return the first non-null expression among its arguments, just like in other SQL databases. It's commonly used to handle null values by substituting them with default values.

Here's the syntax for the COALESCE function in Greenplum:

COALESCE(expression1, expression2, ...)

- expression1, expression2, etc.: These are the expressions or values to be evaluated. They can be columns, literals, or any valid expressions.

Let's see an example to understand how COALESCE works in Greenplum:

Suppose we have a table named employees with columns name, salary, and bonus. Some employees have bonuses, while others do not. We want to select the salary and bonus for each employee, but if a bonus is NULL, we want to replace it with a default value of 0.

SELECT 

    name,

    salary,

    COALESCE(bonus, 0) AS bonus

FROM 

    employees;

In this query:

- We select the name and salary columns directly.

- We use COALESCE(bonus, 0) to select the bonus column. If bonus is NULL for any employee, it will be replaced with 0.

This ensures that even if an employee's bonus is NULL, the query will still return a value (0) for the bonus.

Here's another example demonstrating the use of COALESCE with literal values:

SELECT 

    name,

    COALESCE(salary, 1000) AS salary

FROM 

    employees;

In this query, if an employee's salary is NULL, it will be replaced with 1000.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.