In this tutorial, you will learn how to use the PostgreSQL IF ELSE statements to execute a command based on a specific condition.
if-then statement
The if statement works when the condition is true.
Below is the simplest form of the if statement:
1 2 3 | if condition then statements; end if; |
if-then-else statement
The if…then…else statement executes the statements in the if branch if the condition evaluates to true; otherwise, it executes the statements in the else branch.
Here’s the syntax:
1 2 3 4 5 | if condition then statements; else alternative-statements; end if; |
if-then-elsif Statement
Execute one or more statements when a condition is true.
Here’s the syntax:
1 2 3 4 5 6 7 8 9 10 | if condition_1 then statement_1; elsif condition_2 then statement_2 ... elsif condition_n then statement_n; else else-statement; end if; |
Let’s make an example.
If the number entered in value1 is greater than value2, it will be printed as value1 is greater than value2.
While writing this, let’s print the Error Printing Commands using the “raise notice” expression that I mentioned in my related article.
Let’s use the if command on the table. Before that, let’s see our data by querying the table we will be processing.
If the value given in vinputid in our parents table is not found in the number column in the parents, “There is no id related to the entered vinputid record.” Let’s print it.
If the value given in vinputid in our parents table is not found in the number column in the parents, “There is no id related to the entered vinputid record.” Let’s print it.
If there is a record, let’s write the plpgsql sentence that brings us the name in the relevant id.