7.6.5. IF …​ THEN …​ ELSE

Used for

Conditional jumps

Available in

PSQL

Syntax

  1. IF (<condition>)
  2. THEN <compound_statement>
  3. [ELSE <compound_statement>]
Table 84. IF …​ THEN …​ ELSE Parameters
ArgumentDescription

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 BEGIN …​ END

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:

  1. CASE <test_expr>
  2. WHEN <expr> THEN <result>
  3. [WHEN <expr> THEN <result> ...]
  4. [ELSE <defaultresult>]
  5. END
  6. CASE
  7. WHEN <bool_expr> THEN <result>
  8. [WHEN <bool_expr> THEN <result> ...]
  9. [ELSE <defaultresult>]
  10. END

Example in PSQL

  1. ...
  2. C = CASE
  3. WHEN A=2 THEN 1
  4. WHEN A=1 THEN 3
  5. ELSE 0
  6. END;
  7. ...

Example

An example using the IF statement. Assume that the FIRST, LINE2 and LAST variables were declared earlier.

  1. ...
  2. IF (FIRST IS NOT NULL) THEN
  3. LINE2 = FIRST || ' ' || LAST;
  4. ELSE
  5. LINE2 = LAST;
  6. ...

See also

WHILE …​ DO, CASE