Sub topic 1
Conditional Logic with CASE and DECODE in Oracle SQL
Prerequisites
This chapter assumes you can write SELECT statements with WHERE and ORDER BY, that you know the Oracle types NUMBER and VARCHAR2, that you understand NULL as "no value", and that you can use aggregate functions such as SUM and COUNT. The examples use the HR sample schema, which has an employees table.
Why queries need conditional logic
Reports often need different output depending on the data. A report might label departments with readable names, or group salaries into bands. Without conditional logic, you would fetch raw values and transform them in application code. CASE lets the database do this inside the query, so the result arrives in the shape you need.
Simple CASE: matching one expression against values
A simple CASE compares one expression with a list of values:
SELECT employee_id,
department_id,
CASE department_id
WHEN 10 THEN 'Administration'
WHEN 20 THEN 'Marketing'
WHEN 50 THEN 'Shipping'
ELSE 'Other'
END AS department_label
FROM employees;Oracle compares department_id with each WHEN value and returns the result for the first match.
Searched CASE: testing arbitrary conditions
A searched CASE places a full condition after each WHEN. The conditions can use operators such as < and >, and they can test different columns:
SELECT employee_id,
salary,
CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band
FROM employees;Use a simple CASE when you compare one value for equality. Use a searched CASE for ranges or for conditions on several columns.
How CASE picks a branch: first match, ELSE and no ELSE
Oracle tests the WHEN branches from top to bottom and returns the result of the first true condition. It does not test later branches. Order therefore matters. In the salary example, a salary of 3000 matches 'Low' and never reaches the 'Medium' test.
If no WHEN matches and an ELSE exists, Oracle returns the ELSE result. If there is no ELSE, Oracle returns NULL.
In a simple CASE, WHEN NULL never matches, because NULL = NULL is not true. To test for missing values, use a searched CASE with IS NULL:
SELECT employee_id,
commission_pct,
CASE
WHEN commission_pct IS NULL THEN 'No commission'
ELSE 'Has commission'
END AS commission_status
FROM employees;Exercise
For an employee with a salary of 12000, what does the salary_band expression in the searched CASE example return?
Show answer
'High'. The first two conditions are false (12000 is not below 5000 or 10000), so the ELSE branch returns 'High'.