PL/SQL IF Statements π¦¶
Mentor's Note: Life is full of decisions. "IF it rains, take an umbrella." In PL/SQL, IF statements give your code the ability to make decisions based on data. Without them, your code just runs in a straight line. π‘
π The Scenario: The Traffic Light π¶
- Condition: Is the light Red, Yellow, or Green?
- Logic:
- IF Red -> Stop.
- ELSIF Yellow -> Slow Down.
- ELSE -> Go! β
π» 1. IF-THEN (The Simple Choice)¶
The most basic form. It only does something if the condition is TRUE.
DECLARE
v_score NUMBER := 85;
BEGIN
IF v_score > 70 THEN
DBMS_OUTPUT.PUT_LINE('Congratulations! You passed! π');
END IF;
END;
π» 2. IF-THEN-ELSE (The Either/Or)¶
Gives you an alternative if the condition is FALSE.
DECLARE
v_salary NUMBER := 20000;
BEGIN
IF v_salary > 50000 THEN
DBMS_OUTPUT.PUT_LINE('High Income π');
ELSE
DBMS_OUTPUT.PUT_LINE('Regular Income π');
END IF;
END;
π» 3. IF-THEN-ELSIF (The Multi-Choice)¶
Used for multiple conditions. Note: In Oracle, it's spelled ELSIF (no second 'E').
DECLARE
v_marks NUMBER := 45;
BEGIN
IF v_marks >= 80 THEN
DBMS_OUTPUT.PUT_LINE('Grade: A π');
ELSIF v_marks >= 60 THEN
DBMS_OUTPUT.PUT_LINE('Grade: B β¨');
ELSIF v_marks >= 40 THEN
DBMS_OUTPUT.PUT_LINE('Grade: C π');
ELSE
DBMS_OUTPUT.PUT_LINE('Grade: F (Fail) β');
END IF;
END;
π‘οΈ 4. Nested IFs & NULLs (Architect's Note)¶
- Parentheses: Oracle doesn't require parentheses around the condition, but use them if your logic is complex.
- The NULL Trap: If a condition is
IF (v_val = 10), andv_valis NULL, the condition is neither TRUE nor FALSEβit is UNKNOWN. - Tip: Always handle NULLs using
NVLorIS NULLwithin your IF logic to prevent "skipping" code unexpectedly.
π¨ Visual Logic: The Decision Tree¶
graph TD
A[Start] --> B{Condition?}
B -- True --> C[Execution Path 1]
B -- False --> D{Next Condition?}
D -- True --> E[Execution Path 2]
D -- False --> F[ELSE Path]
C --> G[End IF]
E --> G
F --> G