IF-THEN-ELSE

In PL/SQL, the IF-THEN-ELSE statement is used for conditional execution of code blocks. It allows you to control the flow of your program based on specified conditions. The basic syntax of the IF-THEN-ELSE statement in PL/SQL is as follows:

Syntax

IF condition THEN
   -- Code to be executed if the condition is true
ELSIF condition THEN
   -- Code to be executed if another condition is true
ELSE
   -- Code to be executed if none of the above conditions are true
END IF;

Let’s break down the components of the IF-THEN-ELSE statement:

IF: It starts the conditional block, and the subsequent condition is evaluated.
condition: It is the expression or logical test that determines whether the subsequent code should be executed.

THEN: It marks the beginning of the code block to be executed if the condition is true.

ELSIF: Optional keyword used to specify an alternative condition and code block to be executed if the first condition is false.

ELSE: Optional keyword used to specify the code block to be executed if none of the preceding conditions are true.

END IF: It marks the end of the IF-THEN-ELSE block.

Example

Here’s an example of using the IF-THEN-ELSE statement 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!');
   ELSE
      DBMS_OUTPUT.PUT_LINE('Need improvement.');
   END IF;
END;
/

In this example, the program evaluates the value of the grade variable and prints a message based on the grade. If the grade is ‘A’, it prints ‘Excellent!’; if it’s ‘B’, it prints ‘Good job!’; otherwise, it prints ‘Need improvement.’

IF-THEN-ELSE example

  
DECLARE 
	v_out VARCHAR2(50);
	v_num NUMBER:=-7;
BEGIN
    IF v_num = 0 THEN
        v_out := 'The value: '||v_num;
    ELSIF v_num > 0 THEN 
        v_out := 'The value: '||v_num;
    ELSE
        v_out := 'The value of num < 0; num = '||v_num;
    END IF;
DBMS_OUTPUT.put_line(v_out); 
END;

Output:

The value of num < 0; num = -7

The IF-THEN-ELSE statement in PL/SQL is crucial for building conditional logic within your programs, allowing you to make decisions based on different conditions.