Sub topic 2
Making a Decision with IF-THEN
This chapter covers the simplest form of branching in PL/SQL: the IF-THEN statement. It assumes you can write an anonymous block (DECLARE, BEGIN, EXCEPTION, END), declare and assign scalar variables, and run a script with DBMS_OUTPUT enabled. Examples that query tables use the Oracle HR sample schema. The previous chapter covered how a condition evaluates to TRUE, FALSE, or NULL. This chapter shows what an IF does with each of those three results.
The working model
An IF-THEN statement evaluates one condition. If the result is TRUE, the statements between THEN and END IF run. For any other result, which means FALSE or NULL, those statements are skipped and execution continues after END IF.
IF condition THEN
statement_1;
statement_2;
END IF;The statement has four parts:
- The keyword
IF. - A condition, which is any expression that yields a
BOOLEANvalue. - The keyword
THEN, followed by one or more statements. There is noBEGINorENDpair around them. - The closing
END IF;. It is two words, and the semicolon is required.
A first example
DECLARE
l_balance NUMBER := 250;
l_fee NUMBER := 0;
BEGIN
IF l_balance < 500 THEN
l_fee := 15;
DBMS_OUTPUT.PUT_LINE('Low balance fee applied: ' || l_fee);
END IF;
DBMS_OUTPUT.PUT_LINE('Processing finished');
END;
/Because 250 < 500 is TRUE, both statements inside the IF run and the block prints two lines. If you change l_balance to 900, the condition is FALSE. The block then prints only Processing finished.
Any number of statements can sit between THEN and END IF. They can be assignments, SQL statements, procedure calls, loops, or other IF statements.
What counts as a condition
A condition is an expression of type BOOLEAN. These are the common forms:
- Comparisons:
=,<>,<,>,<=,>=. - Predicates:
IS NULL,IS NOT NULL,BETWEEN,IN,LIKE. - Boolean variables, constants, and function calls that return
BOOLEAN. - Combinations built with
AND,OR, andNOT.
Using a Boolean variable directly
A BOOLEAN variable is already a condition, so you do not need to compare it to TRUE.
DECLARE
l_is_member BOOLEAN := TRUE;
l_total NUMBER := 120;
l_discount NUMBER := 0;
BEGIN
IF l_is_member AND l_total >= 100 THEN
l_discount := l_total * 0.10;
END IF;
IF NOT l_is_member THEN
DBMS_OUTPUT.PUT_LINE('Offer a membership');
END IF;
DBMS_OUTPUT.PUT_LINE('Discount: ' || l_discount);
END;
/This prints Discount: 12. Write IF l_is_member THEN, not IF l_is_member = TRUE THEN. The longer form works, but it adds nothing and reads worse. A name such as l_is_member or l_has_errors lets the condition read like a sentence.
Combining conditions
AND requires both sides to be TRUE. OR requires at least one. NOT reverses a result. When you mix them, NOT is evaluated first, then AND, then OR. Use parentheses whenever the intent is not obvious.
IF (l_dept = 50 OR l_dept = 60) AND l_salary > 5000 THEN
l_flag := TRUE;
END IF;Without the parentheses, AND would bind to l_dept = 60 and l_salary > 5000. The result would be different and harder to spot.
Testing the outcome of SQL
A common use of IF-THEN is to react to what a SQL statement did. You can fetch a count or check an implicit cursor attribute such as SQL%ROWCOUNT.
DECLARE
l_count PLS_INTEGER;
BEGIN
SELECT COUNT(*)
INTO l_count
FROM employees
WHERE department_id = 50;
IF l_count > 0 THEN
DBMS_OUTPUT.PUT_LINE('Department 50 has ' || l_count || ' employees');
END IF;
END;
/COUNT(*) always returns exactly one row, so the SELECT INTO cannot raise NO_DATA_FOUND here. A SELECT of a column value would raise it if no row matched. For that case, handle the exception, or use an aggregate such as COUNT as shown.
SQL%ROWCOUNT holds the number of rows affected by the most recent DML statement. Check it right after the statement and before running any other SQL:
BEGIN
UPDATE employees
SET salary = salary * 1.05
WHERE department_id = 50;
IF SQL%ROWCOUNT = 0 THEN
DBMS_OUTPUT.PUT_LINE('No employees were updated');
END IF;
ROLLBACK;
END;
/The ROLLBACK at the end undoes the raise, so you can run the example repeatedly without changing the sample data.
NULL: the condition that is not FALSE
The IF statement runs its body only when the condition is TRUE. A NULL result is treated like FALSE for that purpose. Any comparison that involves NULL yields NULL, so a missing value can make a condition silently fail.
DECLARE
l_bonus NUMBER := NULL;
BEGIN
IF l_bonus <> 0 THEN
DBMS_OUTPUT.PUT_LINE('Bonus is not zero');
END IF;
IF l_bonus IS NULL OR l_bonus <> 0 THEN
DBMS_OUTPUT.PUT_LINE('Bonus is missing or not zero');
END IF;
END;
/The first IF prints nothing. A reader might expect "not zero" to include a missing bonus, but NULL <> 0 is NULL, so the body is skipped. The second IF prints its line, because l_bonus IS NULL is TRUE.
NOT does not rescue you. NOT NULL is still NULL, so IF NOT (l_bonus = 0) THEN also skips its body when l_bonus is NULL. When a variable can be NULL, decide what the missing value should mean and test for it explicitly with IS NULL or IS NOT NULL. Alternatively, use NVL or COALESCE to replace the NULL with a default before comparing.
A BOOLEAN variable that has never been assigned is also NULL, not FALSE. IF l_done THEN skips its body in that case. It behaves the same as a FALSE value, but IF NOT l_done THEN skips its body too.
Short-circuit evaluation
PL/SQL can stop evaluating a condition as soon as the result is known. In a AND b, if a is FALSE, b does not need to be evaluated. In a OR b, if a is TRUE, b is skipped. Oracle documents this short-circuit behavior for AND and OR. A later chapter covers it in detail, but one consequence matters now: put the cheap or guarding test first.
DECLARE
l_divisor NUMBER := 0;
l_value NUMBER := 100;
BEGIN
IF l_divisor <> 0 AND l_value / l_divisor > 5 THEN
DBMS_OUTPUT.PUT_LINE('Ratio is above 5');
END IF;
DBMS_OUTPUT.PUT_LINE('No error raised');
END;
/The first test is FALSE, so the division is never evaluated and no ZERO_DIVIDE is raised. Do not rely on evaluation order for side effects, such as a function that writes to a table. Use ordering only to avoid errors and unnecessary work.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `ENDIF;` or `END;` instead of `END IF;` | Compilation error (PLS-00103) | Write `END IF;` as two words |
| Missing `THEN` | Compilation error (PLS-00103) | Add `THEN` after the condition |
| Missing semicolon after `END IF` | Compilation error | End with `END IF;` |
| `IF x == 5 THEN` | Compilation error | Use a single `=` for comparison |
| `IF x := 5 THEN` | Compilation error, since `:=` is assignment and not a condition | Use `=` |
| `IF l_flag = NULL THEN` | Never TRUE, since the result is always NULL | Use `IS NULL` |
| `IF (l_x > 5) THEN ... ;` with a stray `;` after `THEN` | Syntax error | No semicolon after `THEN` |
| Using `IF` inside a SQL statement | Compilation error | Use a `CASE` expression in SQL |
A BOOLEAN is a PL/SQL type. In Oracle versions before 23ai, you cannot select a BOOLEAN from a table column or bind one in plain SQL. Convert it to a number or a string first.
Nesting is allowed
The statements inside an IF can include another IF. Each IF needs its own END IF;. The next chapters cover ELSE and ELSIF, which handle the case where the condition is not TRUE, and nested decisions in more depth.
Exercise
What does this block print, and why? DECLARE lqty NUMBER; BEGIN IF lqty <= 10 THEN DBMSOUTPUT.PUTLINE('Small order'); END IF; IF lqty IS NULL THEN DBMSOUTPUT.PUT_LINE('Quantity missing'); END IF; END;
Show answer
It prints only "Quantity missing". The variable l_qty is uninitialized, so it is NULL. The comparison NULL <= 10 yields NULL, and an IF body runs only when the condition is TRUE, so "Small order" is skipped. The IS NULL test is TRUE, so the second message prints.
Exercise
Write an IF-THEN statement that sets lmsg to 'Review' only when lamount is greater than 1000 and lapproved is a BOOLEAN that is FALSE. Make sure the code behaves sensibly if lapproved is NULL, and say how it behaves.
Show answer
IF lamount > 1000 AND NOT lapproved THEN lmsg := 'Review'; END IF; This works when lapproved is TRUE or FALSE. If lapproved is NULL, NOT lapproved is NULL, so the whole condition is not TRUE and lmsg is not set. To treat NULL as not approved, write: IF lamount > 1000 AND (lapproved IS NULL OR NOT lapproved) THEN l_msg := 'Review'; END IF;