Sub topic 7
CASE Expressions Versus CASE Statements
Assume you know basic SELECT, PL/SQL block structure, variables, and assignments. This chapter focuses on choosing between a CASE statement, which controls actions, and a CASE expression, which produces a value.
The key difference
A CASE statement decides which PL/SQL statements to run. It belongs in the executable part of a block and ends with END CASE.
A CASE expression decides which value to return. It can appear wherever an expression is allowed, such as the right side of an assignment. It ends with END.
| Construct | Main purpose | Ending |
|---|---|---|
| CASE statement | Choose actions to execute | `END CASE` |
| CASE expression | Calculate and return a value | `END` |
CASE statements
A simple CASE statement compares one selector with several values:
DECLARE
l_status VARCHAR2(1) := 'A';
BEGIN
CASE l_status
WHEN 'A' THEN
DBMS_OUTPUT.PUT_LINE('Active');
WHEN 'I' THEN
DBMS_OUTPUT.PUT_LINE('Inactive');
ELSE
DBMS_OUTPUT.PUT_LINE('Unknown status');
END CASE;
END;
/The selector, l_status, is evaluated once. Oracle compares it with each WHEN value in order. Only the first matching branch runs.
A searched CASE statement places a condition after each WHEN. This is useful when conditions use ranges or different variables:
DECLARE
l_score NUMBER := 85;
BEGIN
CASE
WHEN l_score >= 90 THEN
DBMS_OUTPUT.PUT_LINE('High');
WHEN l_score >= 70 THEN
DBMS_OUTPUT.PUT_LINE('Medium');
ELSE
DBMS_OUTPUT.PUT_LINE('Low');
END CASE;
END;
/The conditions are checked from top to bottom. Ordering matters because the first true condition wins.
CASE expressions
A CASE expression returns one value. Store that value, pass it to a procedure, or use it in a larger expression:
DECLARE
l_score NUMBER := 85;
l_label VARCHAR2(10);
BEGIN
l_label := CASE
WHEN l_score >= 90 THEN 'High'
WHEN l_score >= 70 THEN 'Medium'
ELSE 'Low'
END;
DBMS_OUTPUT.PUT_LINE('Level: ' || l_label);
END;
/Every result should be compatible with the target variable's data type. For example, do not return text in one branch and a date in another unless you deliberately convert the values.
A CASE expression without ELSE returns NULL when no condition matches. Adding ELSE makes the fallback explicit and prevents unexpected missing values.
Choosing between them
Use a CASE statement when branches perform actions such as inserting rows, calling procedures, or printing messages. Use a CASE expression when every branch supplies a value for an assignment, calculation, or SQL statement.
A CASE statement with no matching WHEN and no ELSE raises CASE_NOT_FOUND. A CASE expression instead returns NULL when it has no matching branch and no ELSE.
Exercise
Which construct should assign the text Late or On time to l_message based on l_due_date < SYSDATE?
Show answer
Use a CASE expression: l_message := CASE WHEN l_due_date < SYSDATE THEN 'Late' ELSE 'On time' END;