Control Structures  «Prev  Next»

Lesson 2 IF-THEN-ELSE statements
Objective Build logic using the IF-THEN-ELSE and ELSIF statements.

IF-THEN-ELSE statements using PL/SQL

You can build logic within your PL/SQL block to execute a sequence of statements based on a particular condition. The selection structure tests a condition then executes one sequence of statements instead of another, depending on the condition. There are three forms of IF statements.

IF-THEN Structure

This sequence of statements executes only if the conditi evaluates to TRUE. If the condition evaluates to FALSE or NULL, the IF statement does nothing. In either case, the control passes to the next statement.

Oracle if then statement
IF condition_1 is TRUE THEN
  statement_1,..., statement_n
END IF;
Oracle IF-THEN statement

IF-THEN-ELSE structure

The sequence of statements in the ELSE clause is executed only if the condition evaluates to FALSE or NULL. The ELSE clause ensures that a sequence of statements is executed. The ELSE clause can include IF statements (nested IF). This construct allows selection of action from several mutually exclusive alternatives. An IF statement can have any number of ELSIF clauses, but the final ELSE clause is optional. Conditions are evaluated one by one from top to bottom as described in the MouseOver below.
Notice that the ELSEIF word is spelled as ELSIF, with a missing E, within PL/SQL.

Oracle if then statement
  1. condition_1: First condition that will be evaluated.
  2. condition_2: Next condition that will be evaluated.
  3. statement_1,...,statement_n: A sequence of statements that PL/SQL will execute if condition_1 evaluates to TRUE.
  4. statement_11,...,statement_n1: A sequence of statements that PL/SQL will execute if condition_2 evaluates to TRUE.
  5. statement_12,...,statement_n2: A sequence of statements that PL/SQL will execute if both condition_1 and condition_2 evaluate to FALSE.
  6. current_reorder_count < re_order_quantity: First condition that will be evaluated.
  7. pets_to_order := re_order_quantity - current_reorder_count
  8. current_reorder_count < re_order_quantity - First condition that will be evaluated.
  9. pets_to_order := re_order_quantity - current_reorder_count - This statement will be executed if the value of current_reorder_count is less than the value of re_order_quantity.
  10. current_reorder_count is greater than re_order_quantity
  11. This statement is executed if the ELSEIF clause is true
  12. ELSE clause is executed if the other conditions are not true

If-then-else-syntax
You can have any number of IF clauses nested within an IF clause. However, you can have only one ELSE clause for every IF clause. In the next lesson, you will learn to build a PL/SQL block with the IF clause through an evaluative simulation.

Oracle PL/SQL Programming