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

Friday, 16 February 2024

COALESCE in TERADATA

In Teradata, the COALESCE() function works similarly to its usage in other database management systems like MySQL. It returns the first non-null expression in a list of expressions.

Here's the syntax:

COALESCE(expression1, expression2, ..., expressionN)

- expression1, expression2, ..., expressionN are the expressions or values to be evaluated.

Let's see an example using a similar scenario as before, but this time we'll use Teradata syntax:

Suppose we have a table employees with columns id, name, salary, and bonus. Some employees might not have a bonus specified, and we want to display a default value of 0 for their bonus.

CREATE TABLE employees (

    id INT,

    name VARCHAR(100),

    salary DECIMAL(10, 2),

    bonus DECIMAL(10, 2)

);

INSERT INTO employees (id, name, salary, bonus) VALUES

(1, 'John', 50000.00, 2000.00),

(2, 'Alice', 60000.00, NULL),

(3, 'Bob', 55000.00, NULL);

Now, let's use COALESCE() to handle null values in the bonus column:

SELECT 

    id,

    name,

    salary,

    COALESCE(bonus, 0) AS bonus

FROM 

    employees;

This query will return:

| id | name  | salary   | bonus  |

|----|-------|----------|--------|

| 1  | John  | 50000.00 | 2000.00|

| 2  | Alice | 60000.00 | 0.00   |

| 3  | Bob   | 55000.00 | 0.00   |

As you can see, for employees without a bonus specified (like Alice and Bob), COALESCE() returns 0 as the default value. For John, who has a bonus specified, it returns the actual bonus value. This behavior is consistent with the usage of COALESCE() across different database systems.

No comments:

Post a Comment

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