Sub topic 5
The Simple CASE Statement
Assume you know basic SQL, anonymous PL/SQL blocks, scalar variables, and how to run a block with DBMS_OUTPUT enabled.
A simple CASE statement chooses one branch by comparing a single value with several possible values. It evaluates the selector once, checks the WHEN values from top to bottom, and runs the first matching branch.
Basic Syntax
CASE selector
WHEN value_1 THEN
statements_1;
WHEN value_2 THEN
statements_2;
ELSE
statements_else;
END CASE;The ELSE branch is optional. Each WHEN value is compared with the selector using equality. After one branch runs, PL/SQL skips the remaining branches and continues after END CASE;.
This is a statement, so it performs actions such as assigning a variable or printing a message. The statement ends with END CASE;, including the semicolon after CASE.
A Worked Example
The following block classifies an order using its status code:
DECLARE
l_status CHAR(1) := 'S';
BEGIN
CASE l_status
WHEN 'N' THEN
DBMS_OUTPUT.PUT_LINE('New order');
WHEN 'P' THEN
DBMS_OUTPUT.PUT_LINE('Order is being processed');
WHEN 'S' THEN
DBMS_OUTPUT.PUT_LINE('Order shipped');
WHEN 'C' THEN
DBMS_OUTPUT.PUT_LINE('Order cancelled');
ELSE
DBMS_OUTPUT.PUT_LINE('Unknown order status');
END CASE;
END;
/The selector is l_status. Its value is 'S', so PL/SQL compares it with 'N', then 'P', then 'S'. The third comparison matches, and the block prints:
Order shippedThe order of the branches matters when you later change the values or the surrounding logic. Put the expected cases in a clear order, and keep the ELSE branch for unexpected or unsupported values.
How PL/SQL Chooses a Branch
Important Edge Cases
A simple CASE compares values for equality. It does not test ranges or general conditions. For example, WHEN l_score >= 70 is not a simple CASE alternative. A searched CASE is more suitable for that form.
NULL also needs care. In Oracle, comparing NULL with = does not produce TRUE. Therefore, this branch does not match a null selector:
CASE l_status
WHEN NULL THEN
DBMS_OUTPUT.PUT_LINE('Missing status');
END CASE;Use an explicit null test in a searched CASE or an IF statement instead.
If no WHEN value matches and there is no ELSE, PL/SQL raises the predefined CASE_NOT_FOUND exception. In production code, an ELSE branch often makes unexpected values visible without allowing this exception to stop the block.
Exercise
What does this block print, and why? DECLARE l_code CHAR(1) := 'X'; BEGIN CASE l_code WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active'); ELSE DBMS_OUTPUT.PUT_LINE('Other'); END CASE; END; /
Show answer
It prints Other because l_code does not equal 'A', so the ELSE branch runs.