-
+
PL/pgSQL - SQL Procedural Language
IF> and CASE> statements let you execute
alternative commands based on certain conditions.
-
PL/pgSQL> has five forms of IF>:
+
PL/pgSQL> has three forms of IF>:
-
-
IF ... THEN ... ELSE IF>>
-
IF ... THEN ... ELSIF ... THEN ... ELSE>>
-
-
IF ... THEN ... ELSEIF ... THEN ... ELSE>>
-
- and four forms of CASE>:
+ and two forms of CASE>:
-
-
CASE ... WHEN ... THEN ... END CASE>>
-
CASE ... WHEN ... THEN ... ELSE ... END CASE>>
-
-
CASE WHEN ... THEN ... END CASE>>
-
CASE WHEN ... THEN ... ELSE ... END CASE>>
IF-THEN-ELSE statements add to
IF-THEN by letting you specify an
alternative set of statements that should be executed if the
- condition evaluates to false.
+ condition is not true. (Note this includes the case where the
+ condition evaluates to NULL.)
-
IF-THEN-ELSE IF>
-
- IF statements can be nested, as in the
- following example:
-
-IF demo_row.sex = 'm' THEN
- pretty_sex := 'man';
-ELSE
- IF demo_row.sex = 'f' THEN
- pretty_sex := 'woman';
- END IF;
-END IF;
-
-
-
- When you use this form, you are actually nesting an
- IF statement inside the
- ELSE part of an outer IF
- statement. Thus you need one END IF
- statement for each nested IF and one for the parent
- IF-ELSE. This is workable but grows
- tedious when there are many alternatives to be checked.
- Hence the next form.
-
-
-
-
-
IF-THEN-ELSIF-ELSE>
+
IF-THEN-ELSIF>
IF boolean-expression THEN
- IF-THEN-ELSIF-ELSE> provides a more convenient
- method of checking many alternatives in one statement.
- Functionally it is equivalent to nested
- IF-THEN-ELSE-IF-THEN> commands, but only one
- END IF> is needed.
+ Sometimes there are more than just two alternatives.
+ IF-THEN-ELSIF> provides a convenient
+ method of checking several alternatives in turn.
+ The IF> conditions are tested successively
+ until the first one that is true is found. Then the
+ associated statement(s) are executed, after which control
+ passes to the next statement after END IF>.
+ (Any subsequent IF> conditions are not>
+ tested.) If none of the IF> conditions is true,
+ then the ELSE> block (if any) is executed.
END IF;
-
-
-
IF-THEN-ELSEIF-ELSE>
+ The key word ELSIF> can also be spelled
+ ELSEIF>.
+
- ELSEIF> is an alias for ELSIF>.
-
+ An alternative way of accomplishing the same task is to nest
+ IF-THEN-ELSE statements, as in the
+ following example:
+
+IF demo_row.sex = 'm' THEN
+ pretty_sex := 'man';
+ELSE
+ IF demo_row.sex = 'f' THEN
+ pretty_sex := 'woman';
+ END IF;
+END IF;
+
+
+
+ However, this method requires writing a matching END IF>
+ for each IF>, so it is much more cumbersome than
+ using ELSIF> when there are many alternatives.
+
+ This form of CASE> is entirely equivalent to
+ IF-THEN-ELSIF>, except for the rule that reaching
+ an omitted ELSE> clause results in an error rather
+ than doing nothing.
+
+