2.6. Conditional Logic

The world is a very complicated place, and the software we write is generally intended to reflect some part of that complexity. So we need constructs in our programming language that can respond to all sorts of situations and requirements, including conditional behavior, such as: "if x is true, then do y, otherwise do z." Enter the IF and CASE statements.

2.6.1. IF Statements

PL/SQL supports conditional logic with the IF statement:

IF condition1
THEN
   statements
[ ELSIF condition2
THEN
   statements ] ...
[ ELSIF conditionn
THEN
   statements ]
[ ELSE
   last_statements ]
END IF;

Where:

conditionn

An expression that yields a Boolean result. Typically, each condition in an IF statement is mutually exclusive from the others.

statements, last_statements

One or more executable statements that execute when the corresponding condition is true. As usual, each statement must have a terminator (closing semi-colon).

The basic idea is that you can test for any number of conditions, and the first one that is true causes the corresponding statement to execute. If none are true, and the ELSE clause is present, last_statements execute.

Here is a simple IF statement:

IF book_count > 10000
THEN
   ready := TRUE;
   DBMS_OUTPUT.PUT_LINE ('We''re ready to open the library!');
END IF;

And here is an example of the IF-THEN-ELSE statement that gives a raise to everyone, but a smaller raise if your hourly wage is $10 or greater:

IF hourly_wage < 10 THEN hourly_wage := hourly_wage ...

Get Learning Oracle PL/SQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.