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.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END; |
Below is a selection from the "Employee" table in the DB2 database.
| Employeeid | Employeename | workdepartment | Age | Country | City |
|---|---|---|---|---|---|
| 7001 | Robert | ADM | 25 | India | Chennai |
| 7002 | Jancy | HUM | 35 | America | Newyork |
| 7003 | Brian | OPE | 40 | China | |
| 7004 | Phil | DES | 50 | America | Boston |
| 7005 | Carmen | ADM | 47 | Russia | |
| 7006 | Helen | OPE | 39 | England | London |
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; |
| Employeeid | Employeename | Department |
|---|---|---|
| 7001 | Robert | Administration |
| 7002 | Jancy | Human Resources |
| 7003 | Brian | Operations |
| 7004 | Phil | Design |
| 7005 | Carmen | Administration |
| 7006 | Helen | Operations |
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); |
| Employeeid | Employeename | City | Country |
|---|---|---|---|
| 7004 | Phil | Boston | America |
| 7001 | Robert | Chennai | India |
| 7006 | Helen | London | England |
| 7002 | Jancy | Newyork | America |
| 7003 | Brian | China | |
| 7005 | Carmen | Russia |
If you have any doubts or queries related to this chapter, get them clarified from our Mainframe experts on ibmmainframer Community!