Conditional logic is the backbone of any procedural program, and in Oracle's procedural extension to SQL, the IF ELSE condition in PL/SQL is the primary tool for making decisions at runtime. Even so, whether you are validating user input, applying business rules to salary calculations, or branching between different error-handling paths, the IF statement lets your code react intelligently to data instead of running the same instructions blindly. This guide walks through every form of the conditional statement, shows working examples, and highlights the pitfalls that trip up beginners and experienced developers alike.
Why Conditional Logic Matters in PL/SQL
PL/SQL blocks execute sequentially, one statement after another. And without branching, a program could only ever do one fixed thing. The IF statement changes that by evaluating a Boolean expression — something that resolves to TRUE, FALSE, or NULL — and then choosing which block of code to run.
This matters because real database work is full of exceptions and variations:
- A discount applies only when an order total exceeds a threshold.
- A record must be rejected if a required field is empty.
- An error log should be written only when an exception is raised.
- Different departments follow different approval rules.
Each of these is a decision, and each decision maps naturally to an IF construct That alone is useful..
The Four Forms of the IF Statement
PL/SQL offers four variations of conditional branching. They are not separate features — they are layers of the same structure, each adding a little more flexibility Easy to understand, harder to ignore..
1. IF-THEN: The Simple Conditional
The simplest form runs a block of code only when a condition is true. If the condition is false, the block is skipped entirely and control passes to the next statement And it works..
IF salary > 10000 THEN
DBMS_OUTPUT.PUT_LINE('Senior band');
END IF;
Note the mandatory END IF; — forgetting it is one of the most common syntax errors in PL/SQL.
2. IF-THEN-ELSE: Two-Way Branching
When you need an alternative path, add the ELSE clause. Exactly one of the two branches will execute, never both and never neither.
IF employee_status = 'ACTIVE' THEN
DBMS_OUTPUT.PUT_LINE('Process payroll');
ELSE
DBMS_OUTPUT.PUT_LINE('Skip payroll');
END IF;
3. IF-THEN-ELSIF: Multi-Way Branching
For three or more mutually exclusive outcomes, use ELSIF. PL/SQL evaluates each condition in order from top to bottom and stops at the first one that evaluates to TRUE. All remaining conditions are ignored.
IF score >= 90 THEN
grade := 'A';
ELSIF score >= 80 THEN
grade := 'B';
ELSIF score >= 70 THEN
grade := 'C';
ELSE
grade := 'F';
END IF;
Two details deserve attention here. So second, the order of the conditions is critical. First, the keyword is ELSIF, not ELSEIF and not ELSE IF — those belong to other languages. If you checked score >= 70 first, every score of 70 or above would receive a C, and the higher bands would never be reached No workaround needed..
4. Nested IF: Conditions Inside Conditions
You can place an IF statement inside another IF block when decisions depend on earlier decisions. Nesting is legal at any depth, but readability deteriorates quickly beyond two or three levels Worth keeping that in mind..
IF department_id = 10 THEN
IF years_of_service > 5 THEN
bonus := salary * 0.15;
ELSE
bonus := salary * 0.10;
END IF;
ELSE
bonus := salary * 0.05;
END IF;
How PL/SQL Evaluates Conditions
Understanding evaluation rules prevents subtle bugs.
Short-circuit evaluation. PL/SQL uses short-circuit logic. In the expression a AND b, if a is FALSE, b is never evaluated. In a OR b, if a is TRUE, b is skipped. This is useful for guarding against errors — for example, IF record_exists AND record.value > 0 THEN protects the second check when the first is false That alone is useful..
The NULL trap. A condition involving NULL evaluates to NULL, not FALSE. Since IF treats NULL as "not true," the THEN branch is skipped — but so is the ELSE branch in a plain IF-THEN structure. Consider:
IF bonus IS NOT NULL AND bonus > 0 THEN
...
Writing IF bonus > 0 when bonus is NULL silently falls through. Always test for NULL explicitly with IS NULL or IS NOT NULL That alone is useful..
No implicit type coercion surprises. Comparing a number to a string may trigger implicit conversion, which can raise ORA-01722: invalid number at runtime. Keep comparisons type-consistent.
A Complete Practical Example
The following block combines several forms into a realistic payroll rule:
DECLARE
v_salary NUMBER := 8500;
v_years NUMBER := 7;
v_rating VARCHAR2(10) := 'GOOD';
v_increment NUMBER;
BEGIN
IF v_rating = 'EXCELLENT' THEN
v_increment := 0.12;
ELSIF v_rating = 'GOOD' THEN
IF v_years >= 5 THEN
v_increment := 0.08;
ELSE
v_increment := 0.05;
END IF;
ELSE
v_increment := 0.02;
END IF;
DBMS_OUTPUT.PUT_LINE('Increment: ' || v_increment * 100 || '%');
END;
The outer ELSIF chain handles the rating, while the nested IF refines the outcome based on tenure. This mirrors how business rules are usually written in plain language, which is exactly why the structure is so widely used Not complicated — just consistent..
Common Mistakes to Avoid
- Missing
END IF;— everyIFmust be closed, even single-line ones. - Using
ELSEIForELSE IF— PL/SQL requiresELSIF. - Semicolon after the condition —
IF x > 0; THENis a syntax error. The condition line ends without a semicolon. - **Wrong condition order in
ELSIF
Wrong condition order in ELSIF — branches are tested top to bottom, and the first one that succeeds wins. If a broad test sits above a narrow one, the narrow branch becomes dead code:
IF v_rating LIKE '%GOOD%' THEN -- matches 'EXCELLENT'? No, but it matches 'GOOD' and 'VERY GOOD'
...
ELSIF v_rating = 'GOOD' THEN -- never reached
...
END IF;
Reorder the tests so the most specific condition appears first, or convert the whole chain to a CASE expression, which makes the mutual exclusivity obvious Simple, but easy to overlook..
A few more traps worth checking in a code review:
- Assigning a flag with three lines when one would do.
IF v_valid THEN v_flag := 'Y'; ELSE v_flag := 'N'; END IF;is better written asv_flag := CASE WHEN v_valid THEN 'Y' ELSE 'N' END;— or simplyv_flag := CASE v_valid WHEN TRUE THEN 'Y' ELSE 'N' END;. - Calling a function inside a condition for its side effects. The optimizer and short-circuiting mean the call may not execute at all, or may execute a different number of times than you expect. Keep conditions free of side effects.
- Repeating the same expensive expression in the
IF, theELSIF, and the body. Assign it to a local variable once. - Using
IFfor row-by-row decisions that SQL can express set-based. If the branch only chooses a multiplier, aCASEinside theSELECTorMERGEwill usually outperform a cursor loop.
Choosing Between IF and CASE
Both constructs are correct for multi-way branching, so the choice comes down to intent. On the flip side, use IF ... ELSIF when the tests are unrelated comparisons of different variables or different operators Worth keeping that in mind..
v_band := CASE
WHEN v_salary < 3000 THEN 'Junior'
WHEN v_salary <= 8000 THEN 'Mid'
WHEN v_salary <= 15000 THEN 'Senior'
ELSE 'Executive'
END;
The simple form CASE v_rating WHEN 'GOOD' THEN ... END; is even tighter, but it only works for equality checks and fails silently if v_rating is NULL — another reason to prefer the searched form when the input comes from a column.
Verifying the Branches
Conditional logic is only as good as its test coverage. Exercise every branch, including the ELSE, and include the boundary values: zero, the exact threshold, one above and one below it, and NULL. A quick way to force coverage is a driver block that loops over a collection of representative inputs and prints the chosen path, so a refactor that silently reorders an ELSIF shows up immediately Most people skip this — try not to..
No fluff here — just what actually works.
Conclusion
The IF statement is the workhorse of procedural control flow in PL/SQL: a simple IF-THEN for optional work, IF-THEN-ELSE for two mutually exclusive outcomes, and ELSIF chains for graded rules, with nesting available when a decision genuinely depends on another. The mechanics are easy; the discipline lies in the details. Write type-consistent conditions, test for NULL explicitly rather than assuming a value, order ELSIF branches from most specific to most general, and close every block with END IF; Easy to understand, harder to ignore. And it works..
CASE when the branches are really one value being matched against a set of alternatives. A block that reads top-to-bottom without deep indentation is easier to review, easier to test, and far less likely to hide a branch that can never be reached No workaround needed..
-- Before: three levels of nesting
IF v_status = 'ACTIVE' THEN
IF v_balance > 0 THEN
IF v_overdue THEN
v_action := 'SUSPEND';
END IF;
END IF;
END IF;
-- After: a flat ELSIF chain with the same outcome
IF v_status = 'ACTIVE' AND v_balance > 0 AND v_overdue THEN
v_action := 'SUSPEND';
END IF;
When the individual tests are meaningful on their own, a small helper function keeps the top-level condition readable:
FUNCTION is_suspendable(p_status VARCHAR2, p_balance NUMBER, p_overdue BOOLEAN)
RETURN BOOLEAN IS
BEGIN
RETURN p_status = 'ACTIVE' AND p_balance > 0 AND p_overdue;
END;
With that in place the caller becomes a single line, and the rule it encodes can be unit-tested in isolation.
The broader point is that IF is not just a language feature but a way of expressing policy. This leads to every branch you write is a decision you are committing to, so the structure of the code should mirror the structure of the rule. Keep conditions pure and side-effect free, make NULL handling explicit, order ELSIF arms from specific to general, and prefer the flattest form that still reads clearly. Do that consistently and the control flow stops being a source of subtle bugs and becomes the part of the program that documents exactly what happens, and when And that's really what it comes down to..