Let's understand Mainframe
Home Tutorials Interview Q&A Quiz Mainframe Memes Contact us About us

Module 5: DB2 SQL SELECT and Filtering


CASE

CASE adds if-then-else logic inside SQL. It derives new values from old ones - pay bands from salaries, labels from codes - without changing the stored data.

The two forms of CASE

  • Simple CASE: compares one expression with values: CASE WORKDEPT WHEN 'A00' THEN ...
  • Searched CASE: tests full conditions: CASE WHEN SALARY > 40000 THEN ...
  • Searched CASE is more flexible - conditions can differ per WHEN.
  • Both forms end with END, and can be aliased like a column.

WHEN, THEN and ELSE

  • WHENs are tested in order; the first true WHEN wins.
  • THEN gives the result value for that WHEN.
  • ELSE is the fallback when no WHEN matches - omit it and you get NULL.
  • All THEN/ELSE results should be compatible types.

Where CASE can appear

  • In the SELECT list to compute derived columns.
  • In ORDER BY to sort by a custom ranking.
  • In WHERE to build conditional filters.
  • CASE cannot create new rows or columns in the table - it only computes values in the result.

Example

SELECT EMPNO, LASTNAME, SALARY, CASE WHEN SALARY > 40000 THEN 'HIGH' WHEN SALARY > 30000 THEN 'MEDIUM' ELSE 'LOW' END AS PAY_BAND FROM EMP ORDER BY SALARY DESC; EMPNO LASTNAME SALARY PAY_BAND ------ -------- ------ -------- 000010 HAAS 52750 HIGH 000050 GEYER 40175 HIGH 000030 KWAN 38250 MEDIUM





© copyright mainframebug.com
Privacy Policy
MainframeBug Assistant