7.6.5. IF … THEN … ELSE
Used for
Conditional jumps
Available in
PSQL
Syntax
IF (<condition>)
THEN <compound_statement>
[ELSE <compound_statement>]
Argument | Description |
---|---|
condition | A logical condition returning TRUE, FALSE or UNKNOWN |
single_statement | A single statement terminated with a semicolon |
compound_statement | Two or more statements wrapped in |
The conditional jump statement IF … THEN
is used to branch the execution process in a PSQL module. The condition is always enclosed in parentheses. If it returns the value TRUE, execution branches to the statement or the block of statements after the keyword THEN
. If an ELSE
is present and the condition returns FALSE or UNKNOWN, execution branches to the statement or the block of statements after it.
Multi-branch Jumps
PSQL does not provide multi-branch jumps, such as CASE
or SWITCH
. Nevertheless, the CASE
search statement from DSQL is available in PSQL and is able to satisfy at least some use cases in the manner of a switch:
CASE <test_expr>
WHEN <expr> THEN <result>
[WHEN <expr> THEN <result> ...]
[ELSE <defaultresult>]
END
CASE
WHEN <bool_expr> THEN <result>
[WHEN <bool_expr> THEN <result> ...]
[ELSE <defaultresult>]
END
Example in PSQL
...
C = CASE
WHEN A=2 THEN 1
WHEN A=1 THEN 3
ELSE 0
END;
...
Example
An example using the IF
statement. Assume that the FIRST
, LINE2
and LAST
variables were declared earlier.
...
IF (FIRST IS NOT NULL) THEN
LINE2 = FIRST || ' ' || LAST;
ELSE
LINE2 = LAST;
...
See also