Skip to content

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)

  1. Parentheses: Oracle doesn't require parentheses around the condition, but use them if your logic is complex.
  2. The NULL Trap: If a condition is IF (v_val = 10), and v_val is NULL, the condition is neither TRUE nor FALSEβ€”it is UNKNOWN.
  3. Tip: Always handle NULLs using NVL or IS NULL within 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

πŸ“ˆ Learning Path