TSO-ISPF JCL COBOL VSAM DB2 CICS Tools Articles Job Portal Forum Quiz Interview Q&A

DB2 - SQL Case Statement


The CASE statement goes through conditions and returns a value when the first condition is met (like an COBOL Evaluate statement). So, If a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.

If ELSE part is not added in CASE statement and no conditions are true, it returns NULL value.

syntax:

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;

DB2 Database:

Below is a selection from the "Employee" table in the DB2 database.

EmployeeidEmployeenameworkdepartmentAgeCountryCity
7001RobertADM25IndiaChennai
7002JancyHUM35AmericaNewyork
7003BrianOPE40China
7004PhilDES50AmericaBoston
7005CarmenADM47Russia
7006HelenOPE39EnglandLondon


Example 1:

Assume that in the "Employee" table the first character of a department number represents the division in the organization. Use a CASE expression to list the full name of the division to which each employee belongs.

SELECT Employeeid, Employeename,
       CASE SUBSTR(workdepartment,1,1)
          WHEN 'A' THEN 'Administration'
          WHEN 'H' THEN 'Human Resources'
          WHEN 'D' THEN 'Design'
          WHEN 'O' THEN 'Operations'
       END AS "Department"
   FROM Employee;
Result:
EmployeeidEmployeenameDepartment
7001RobertAdministration
7002JancyHuman Resources
7003BrianOperations
7004PhilDesign
7005CarmenAdministration
7006HelenOperations


Example 2:

The following SQL statement will order the employee by City. However, if City is NULL, then order by Country:

SELECT Employeeid, Employeename, City, Country
    FROM Employee
    ORDER BY
    (CASE
        WHEN City IS NULL THEN Country
        ELSE City
    END);
Result:
EmployeeidEmployeenameCityCountry
7004PhilBostonAmerica
7001RobertChennaiIndia
7006HelenLondonEngland
7002JancyNewyorkAmerica
7003BrianChina
7005CarmenRussia


If you have any doubts or queries related to this chapter, get them clarified from our Mainframe experts on ibmmainframer Community!

Are you looking for Job Change? Job Portal