Control Structures  «Prev  Next»

Lesson 2 IF-THEN-ELSE statements
Objective Build logic using the IF-THEN-ELSE and ELSIF statements in Oracle 26ai

IF-THEN-ELSE Statements in Oracle PL/SQL

Conditional logic is the foundation of any procedural program. In Oracle PL/SQL, the IF statement evaluates a Boolean condition and executes one sequence of statements or another depending on the result. Three forms of the IF statement are available — IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF — each suited to a different level of conditional complexity. This lesson covers all three forms, short-circuit evaluation, nested IF statements, and Oracle 26ai support that affects how Boolean conditions interact with SQL.

Run the examples

The DECLARE/BEGIN examples are complete anonymous blocks. In SQL*Plus or SQLcl, run SET SERVEROUTPUT ON first to display DBMS_OUTPUT text, then submit the block with a slash on its own line. The slash is a client command; END; terminates the PL/SQL block. Other examples are fragments that require surrounding declarations. A NULL; statement is an intentional placeholder action, not an empty branch.

IF-THEN

The IF-THEN form executes its statement block only when the condition evaluates to TRUE. When the condition evaluates to FALSE or NULL, the block is skipped entirely and execution continues at the first statement after END IF. No alternative action is taken.

Oracle if then statement

The legacy image is a conceptual illustration; use the corrected, copyable syntax below. Statements are separated by semicolons, not commas.

IF condition THEN
  NULL; -- replace with one or more statements
END IF;

Example — reorder logic for a pet store inventory system:

IF current_reorder_count < re_order_quantity THEN
  pets_to_order := re_order_quantity - current_reorder_count;
END IF;

The assignment to pets_to_order executes only when stock is below the reorder threshold. If stock meets or exceeds the threshold, the statement is skipped and pets_to_order retains its previous value.

IF-THEN-ELSE

The ELSE clause provides an alternative block that executes when the condition evaluates to FALSE or NULL. Exactly one of the two branches always executes — either the THEN block or the ELSE block, never both and never neither.

IF condition THEN
  NULL; -- replace with the action for TRUE
ELSE
  NULL; -- replace with the alternative action
END IF;

The ELSE clause guarantees that the program always takes an explicit action regardless of the condition result. This is particularly important when the NULL case must be handled — a plain IF-THEN silently does nothing when the condition is NULL, which can leave variables unchanged or NULL when they were declared without an initial value.

IF-THEN-ELSIF

When several conditions must be tested in priority order, the ELSIF clause extends the IF statement with additional branches. Conditions are evaluated sequentially from top to bottom. The first branch whose condition evaluates to TRUE executes, and all remaining branches — including any subsequent ELSIF clauses and the final ELSE — are skipped.

If_then_else syntax

The legacy image is a conceptual illustration; use the corrected, copyable syntax below. Statements are separated by semicolons, not commas.

IF condition_1 THEN
  NULL; -- replace with one or more statements
ELSIF condition_2 THEN
  NULL; -- replace with statements
ELSE
  NULL; -- replace with statements
END IF;

Example — extended reorder logic with commission handling:

commission_for_sales := 0;
IF current_reorder_count IS NULL OR re_order_quantity IS NULL THEN
  RAISE_APPLICATION_ERROR(-20001, 'Stock and threshold are required');
ELSIF current_reorder_count < re_order_quantity THEN
  pets_to_order := re_order_quantity - current_reorder_count;
ELSIF current_reorder_count > re_order_quantity THEN
  pets_to_order        := 0;
  commission_for_sales := 0.10;
ELSE
  pets_to_order := 0;
END IF;

The three branches handle: stock below threshold (order more pets), stock above threshold (no order, apply commission), and stock exactly at threshold (no order, no commission).

Note the spelling carefully — Oracle PL/SQL uses ELSIF, not ELSEIF. Using ELSEIF produces a compile-time error. An IF statement can contain any number of ELSIF clauses. The final ELSE clause is optional but recommended whenever a default action should apply to all unmatched cases.

Boolean Conditions and NULL

PL/SQL uses three-valued logic — a condition can evaluate to TRUE, FALSE, or NULL. NULL in a condition behaves as "unknown" — it is neither true nor false. The practical consequence is that IF NULL THEN does not execute the THEN block. The ELSE block executes instead, or nothing executes if there is no ELSE.

DECLARE
  v_value NUMBER := NULL;
BEGIN
  IF v_value = 10 THEN
    DBMS_OUTPUT.PUT_LINE('Equal to 10');
  ELSIF v_value IS NULL THEN
    DBMS_OUTPUT.PUT_LINE('Value is NULL');
  ELSE
    DBMS_OUTPUT.PUT_LINE('Not equal to 10');
  END IF;
END;
/

The condition v_value = 10 evaluates to NULL when v_value is NULL — not FALSE. To test for NULL explicitly, use the IS NULL predicate rather than an equality comparison.

Short-Circuit Evaluation

Oracle PL/SQL uses short-circuit evaluation when processing logical expressions with AND and OR. The engine stops evaluating as soon as the overall result is determined, without examining the remaining operands. For OR, evaluation stops as soon as any operand is TRUE. For AND, evaluation stops as soon as any operand is FALSE. A NULL operand does not by itself determine the result: NULL AND FALSE is FALSE, whereas NULL AND TRUE is NULL.

Short-circuit evaluation prevents runtime errors that would occur if all operands were always evaluated. The following example demonstrates how a potential divide-by-zero error is avoided — when on_hand is zero, the left operand of the OR expression is TRUE, so PL/SQL never evaluates the right operand:

DECLARE
  on_hand  INTEGER := 0;
  on_order INTEGER := 100;
BEGIN
  -- Short-circuit prevents divide-by-zero:
  -- when on_hand = 0, the left operand is TRUE
  -- and the right operand is never evaluated
  IF (on_hand = 0) OR ((on_order / on_hand) < 5) THEN
    DBMS_OUTPUT.PUT_LINE('On hand quantity is zero.');
  END IF;
END;
/

Expected output for the values shown:

On hand quantity is zero.

If PL/SQL evaluated both operands before applying OR, on_order / on_hand would raise ORA-01476: divisor is equal to zero. Short-circuit evaluation guarantees this never occurs. The same protection applies to AND — if the left operand is FALSE, the right operand is never evaluated regardless of what it contains.

Nested IF Statements

An IF statement can be nested inside the THEN or ELSE block of another IF statement. Nesting allows secondary conditions to be evaluated only when a primary condition is satisfied. Each nested IF requires its own END IF:

IF order_total > 500 THEN
  IF customer_type = 'PREMIUM' THEN
    discount := 0.15;
  ELSE
    discount := 0.10;
  END IF;
ELSE
  discount := 0.05;
END IF;

Deep nesting makes code harder to read. When more than two levels of nesting are required, consider refactoring the logic into a CASE statement or a separate procedure. Each IF clause can have only one ELSE clause — additional alternatives require ELSIF when you intend one chain; a nested IF is a separate statement with its own END IF.

IF-THEN-ELSIF vs CASE — Choosing the Right Construct

When a single variable or expression is compared against several fixed values, a CASE statement is more readable than a chain of ELSIF clauses. When conditions involve different variables, range checks, or complex Boolean expressions, IF-THEN-ELSIF is more appropriate because each ELSIF clause can evaluate an entirely independent condition. A searched CASE statement also supports independent Boolean conditions; choose the form that makes the decision easiest to read.

-- CASE is cleaner when comparing one variable against fixed values
CASE order_status
  WHEN 'PENDING'   THEN process_pending(order_id);
  WHEN 'APPROVED'  THEN process_approved(order_id);
  WHEN 'CANCELLED' THEN process_cancelled(order_id);
  ELSE log_unknown_status(order_id);
END CASE;

-- IF-THEN-ELSIF is more appropriate for independent conditions
IF order_total > 1000 AND customer_type = 'PREMIUM' THEN
  apply_premium_discount(order_id);
ELSIF ship_date < SYSDATE THEN
  flag_overdue_shipment(order_id);
ELSE
  process_standard_order(order_id);
END IF;

Oracle 26ai and SQL BOOLEAN

Oracle 26ai supports the SQL BOOLEAN type introduced in the Oracle 23c/23ai generation. PL/SQL already supported BOOLEAN in earlier releases. Conditional expressions that produce a BOOLEAN result can now be used directly in SQL contexts — not just inside PL/SQL blocks. This affects how IF conditions interact with SQL queries. A PL/SQL function returning BOOLEAN can now be called directly from SQL without a wrapper:

This schema-dependent example assumes a customers table with customer_id, customer_name, and customer_type columns. The function propagates NO_DATA_FOUND when its lookup finds no row.

-- Oracle 26ai -- BOOLEAN return type callable directly from SQL
CREATE OR REPLACE FUNCTION is_premium_customer(
  p_customer_id IN NUMBER
) RETURN BOOLEAN IS
  v_type customers.customer_type%TYPE;
BEGIN
  SELECT customer_type INTO v_type
  FROM   customers
  WHERE  customer_id = p_customer_id;
  RETURN v_type = 'PREMIUM';
END;
/

-- Call directly in SQL without a wrapper function
SELECT customer_id, customer_name
FROM   customers
WHERE  is_premium_customer(customer_id);

In earlier releases such as Oracle 19c, the WHERE clause above would have raised an error because SQL could not handle a BOOLEAN return type. A wrapper returning VARCHAR2('Y'/'N') or NUMBER(1/0) was required. Oracle 26ai eliminates this workaround entirely.

Reference: Oracle PL/SQL conditional selection statements.

Summary

The three forms of the PL/SQL IF statement — IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF — provide conditional branching for all levels of complexity. Conditions follow three-valued logic: TRUE, FALSE, and NULL. Test for NULL explicitly with IS NULL rather than equality comparisons. Short-circuit evaluation prevents runtime errors in complex Boolean expressions by stopping evaluation as soon as the result is determined. Use ELSIF — not ELSEIF — for multiple branches, and prefer CASE when a single variable is compared against fixed values. In Oracle 26ai, functions returning BOOLEAN can be called directly from SQL, eliminating the wrapper functions that were previously required for SQL-PL/SQL Boolean interoperability. The next lesson covers building a PL/SQL block with the IF clause through an evaluative simulation.


SEMrush Software 2 SEMrush Banner 2