if-then
Statements are the IF
simplest form of a control statement and are often used to make decisions and change the control flow of program execution.
IF
A statement associates a condition with THEN
a keyword and END IF
a sequence of statements that it contains. If the condition is TRUE
, the statement will be executed, and if the condition is FALSE
or NULL
, the IF
statement block will not take any action.
Grammar
IF-THEN
The syntax of the statement is-
IF condition THEN S; END IF;
Here, condition
a Boolean or relational condition S
is a simple or compound statement. Here is IF-THEN
An example of a statement-
IF (a <= 20) THEN c:= c+1;END IF;
If the Boolean expression condition evaluates to true
, the if
code block in the statement is executed. If the Boolean expression evaluates to false
, the if
first set of code after the end of the statement (after the end) is if
executed.
Flow chart
Example-1
Let's take a look at an example to understand the above implementation process-
DECLARE a number(2) := 10; BEGIN a:= 10; -- check the boolean condition using if statement IF( a < 20 ) THEN -- if condition is true then print the following dbms_output.put_line(‘a is less than 20 ‘ ); END IF; dbms_output.put_line(‘value of a is : ‘ || a); END; /
When the above code executes at the SQL prompt, it produces the following results-
a is less than 20 value of a is : 10 PL/SQL procedure successfully completed.
Example-2
We have created a table and several records in the PL/SQL variable type, referring to the following statements to manipulate the tables and data-
DECLARE c_id customers.id%type := 1; c_sal customers.salary%type; BEGIN SELECT salary INTO c_sal FROM customers WHERE id = c_id; IF (c_sal <= 2000) THEN UPDATE customers SET salary = salary + 1000 WHERE id = c_id; dbms_output.put_line (‘Salary updated‘); END IF; END; /
When the above code executes at the SQL prompt, it produces the following results-
Salary updated PL/SQL procedure successfully completed.
PL/SQL If-then statements