IF-THEN-ELSIF

The IF-THEN-ELSIF statement is a control structure in PL/SQL used for conditional execution of code blocks.

Syntax

Here is a brief overview of the PL/SQL IF-THEN-ELSIF statement:

IF condition1 THEN
   -- statements to be executed if condition1 is true
ELSIF condition2 THEN
   -- statements to be executed if condition2 is true
ELSIF condition3 THEN
   -- statements to be executed if condition3 is true
...
ELSE
   -- statements to be executed if none of the conditions are true
END IF;

IF: The initial condition that is evaluated. If it is true, the associated block of statements is executed.

ELSIF: If the initial condition is false, the subsequent ELSIF conditions are evaluated one by one. The block of statements associated with the first true condition is executed, and the rest are skipped.

ELSE: If none of the conditions are true, the block of statements following the ELSE keyword is executed. It serves as a catch-all for situations where none of the specified conditions are met.

END IF: Marks the end of the IF-THEN-ELSIF block.

Example

Here’s an example to illustrate the usage of IF-THEN-ELSIF in a PL/SQL block:

DECLARE
   grade CHAR(1) := 'B';
BEGIN
   IF grade = 'A' THEN
      DBMS_OUTPUT.PUT_LINE('Excellent!');
   ELSIF grade = 'B' THEN
      DBMS_OUTPUT.PUT_LINE('Good job!');
   ELSIF grade = 'C' THEN
      DBMS_OUTPUT.PUT_LINE('Fair.');
   ELSE
      DBMS_OUTPUT.PUT_LINE('Needs improvement.');
   END IF;
END;

In this example, the code checks the value of the variable ‘grade’ and prints a message based on its value. The first true condition encountered is executed, and if none are true, the ELSE block is executed. The output will be “Good job!” since the grade variable is set to ‘B’.

IF-THEN-ELSIF example

  
DECLARE 
	v_out VARCHAR2(50);
	v_num NUMBER:=8;
	v_name VARCHAR2(100):='XYZ';
BEGIN
    IF v_num = 2 THEN
        NULL;
    ELSIF v_num = 8 THEN
        v_out := 'The value: '||v_num;
        DBMS_OUTPUT.put_line(v_out);     
    END IF;
    
    IF v_name = '123' THEN
		NULL;
    ELSIF v_name = 'XYZ' THEN  
		DBMS_OUTPUT.put_line(v_name);    
    END IF;
END;

Output:

The value: 8

XYZ