Updated May 10, 2023
Introduction to PostgreSQL For Loop
In the PostgreSQL database, we can use many conditional and looping statements. In this article, we will learn what is looping, why it is required, and the various types of looping statements, and how we can use for loop in PostgreSQL functions to achieve our intention or get our work done.
What Is Looping?
We often face a situation where we have to perform a specific activity multiple times in a repetitive fashion. In programming, looping through statements is a common technique in the technical world. Whenever we want to perform a certain task repetitively, we can loop through those statements that we want to perform repetitively. You can use a loop to execute statements for a specific number of times or until your requirement is fulfilled.
Types of Loops
In PostgreSQL, we have various types of looping facilities. We can stop looping with a plain loop with the EXIT WHEN statement. Another type of looping statement is the loop, and the last one is the while loop. To understand the examples, you need to have basic knowledge of PostgreSQL functions and CRUD operation statements like SELECT, UPDATE, INSERT and DELETE. Other than this, you should be aware of the arrays in PostgreSQL.
FOR [counting variable name] IN [REVERSE] [START VALUE] .. [END VALUE] [BY step value] LOOP [code/statements to repeat]; END LOOP;
For loop contains a counting variable that is unnecessary to declare outside the loop. You can declare it in the for loop statement itself. This counting variable has a START VALUE and an END VALUE as its range for which it will iterate. The step value is the stepping amount that specifies how much value is to be skipped from the start value till the end value while iterating. And the LOOP keyword marks the beginning of the for loop’s body that will be executed each time the loop is iterated.
You include the statements that you want to execute on a repetitive basis in the [code/statements to repeat] section, and the END LOOP marks the end of the for loop’s operation.REVERSE is the optional parameter in which, when specified, the counting variable will be decremented while iterating instead of incrementing each time the iteration is done. The for loop can be placed inside a certain function’s body, and this function can be called whenever we have to execute the for loop defined by us. It is necessary to define the range such that the looping should come to a halt and not iterate infinitely. Doing so will result in a wastage of CPU memory and execution and sometimes may crash the system.
Examples to Implement in PostgreSQL For Loop
Below are some examples of PostgreSQL For Loop:
Let us first consider a simple example of printing the table of a particular integer that we pass to our function. Let us begin to be creating our function.
CREATE OR REPLACE FUNCTION displayTable(int) RETURNS void AS $$ DECLARE tableOf int:=$1; BEGIN FOR counter IN 1..10 LOOP RAISE NOTICE '%', tableOf*counter; END LOOP; END; $$ LANGUAGE plpgsql;
So, after copying and pasting the above function in your psql command prompt, a function named displayTable will be created if CREATE FUNCTION is displayed at the end.
Now, to print the table, we will have to call the function displayTable() in the following way:
Hence for printing the table of 5, the 5 number is multiplied by 1,2 and so on till 10, and a notice is displayed to print the table on the console. The for loop iterates 10 times to print any table.
Reverse Order Looping: In this, we will see where our counter will decrement in value whenever it iterates in the for loop instead of incrementing. This functionality can be brought simply by specifying REVERSE after a counter variable is declared in for statement. Let’s consider an example where the function prints numbers in decreasing order from the number passed to it until 1.
CREATE OR REPLACE FUNCTION reverseExample(int) RETURNS void AS $$ DECLARE passedValue int:=$1; BEGIN FOR sampleCounter IN REVERSE passedValue..1 LOOP RAISE NOTICE 'My Current Value is = %', sampleCounter; END LOOP; END; $$ LANGUAGE plpgsql;
After running the above function, it will give the following:
Now, to print the values, we will have to write the select statement in the following way –
Step value other than 1: Suppose we have to print all the even numbers from 11 to 30. Then it is quite obvious that the first even number is 12, and after every 1 number, an even number comes. Hence if we increment by 2, then even numbers will print. Let us write a function for the same.
CREATE OR REPLACE FUNCTION displayEvenNumbers(int,int) RETURNS void AS $$ DECLARE first int; last int:=$2; BEGIN IF $1%2=0 THEN first=$1; ELSE first=$1+1; END IF; FOR sampleCounter IN first..last BY 2 LOOP RAISE NOTICE 'Even numbers : %', sampleCounter; END LOOP; END; $$ LANGUAGE plpgsql;
For getting even numbers, we will query the following statement.
Iterating an array using foreach.
CREATE FUNCTION displayRowValues(int) RETURNS void AS $$ DECLARE sampleArray int; BEGIN FOREACH sampleArray SLICE 1 IN ARRAY $1 LOOP RAISE NOTICE 'The Row Value is = %', sampleArray; END LOOP; END; $$ LANGUAGE plpgsql;
Copy and paste the above code in your PostgreSQL /psql command prompt to create a function named displayRowValues that will return the value and print the notice for each row of the array passed the function while calling it.
If you successfully create the function, PostgreSQL will display the CREATE FUNCTION statement after you copy and paste the above function definition and execute it. Now for calling the displayRowValues(), we will have to pass a parameter which should be an array. We will pass an array that will have the following values –
which in graphical form is as follows –
Now, our calling statement will be
The RAISE NOTICE ‘The Row Value is = %’, sampleArray; statement will execute for each row of the array that we have passed, and the notice for each row will be printed. Hence, the output of the above query statement will be as follows.
You can use the for loop effectively and conveniently in PostgreSQL according to your necessity to loop around or execute certain statements repetitively. In PostgreSQL, you can iterate through the result set retrieved from a particular query using a for loop.
We hope that this EDUCBA information on “PostgreSQL For Loop” was beneficial to you. You can view EDUCBA’s recommended articles for more information.