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

Wednesday, 21 February 2024

CASE Statement in DB2

In DB2, the CASE statement is used for conditional logic within SQL queries, similar to other SQL databases. Here's the syntax of the CASE statement in DB2 along with an example:


SELECT

    employee_id,

    first_name,

    last_name,

    salary,

    CASE

        WHEN salary >= 100000 THEN 'High Salary'

        WHEN salary >= 50000 THEN 'Medium Salary'

        ELSE 'Low Salary'

    END AS salary_category

FROM

    employees;


In this example, let's assume there's a table named employees with columns employee_id, first_name, last_name, and salary. We want to categorize employees based on their salary ranges:


- If the salary is greater than or equal to 100,000, the employee is categorized as having a "High Salary".

- If the salary is between 50,000 and 99,999, the employee is categorized as having a "Medium Salary".

- If the salary is less than 50,000, the employee is categorized as having a "Low Salary".


The CASE statement evaluates each condition sequentially and returns the result associated with the first condition that evaluates to true. If none of the conditions are met, the ELSE clause provides a default result.


You can use the CASE statement in DB2 for more complex conditional logic within your SQL queries. Just adjust the conditions and result expressions based on your specific requirements and data schema.

No comments:

Post a Comment

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