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. This is programming, and the technical world is called looping through the statements. Whenever we want to perform a certain task repetitively, we can loop through those statements that we want to perform repetitively. We can loop the statements for a specific number of times or until and unless our requirement is fulfilled.
Types of Loops
In PostgreSQL, we have various types of looping facilities. We can use a plain loop with the EXIT WHEN statement to stop looping. 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.
Syntax :
FOR [counting variable name] IN [REVERSE] [START VALUE] .. [END VALUE] [BY step value]
LOOP
[code/statements to repeat];
END LOOP;
Explanation:
For loop contains a counting variable which is not necessary to declare outside the for a loop. It can be declared in the for loop statement itself. This counting variable has 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 will be iterated.
The statements that we want to execute on a repetitive basis are included in the [code/statements to repeat] section, and END LOOP marks the ending of the for loop working. REVERSE is the optional parameter 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 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:
Example #1
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.
Code:
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.
Output:
Now, to print the table, we will have to call the function displayTable() in the following way:
select displayTable(5);
Output:
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.
Example #2
Reverse Order Looping: In this, we will see where our counter will decrement in value whenever it will iterate 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 us see an example where the numbers will print in the decreasing order from the number which is passed to function until 1.
Code:
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:
Output:
Now, to print the values, we will have to write the select statement in the following way –
select reverseExample(12);
Output:
Example #3
Step value other than 1: Now, 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 and even number comes. Hence if we increment by 2, then even numbers will print. Let us write a function for the same.
Code:
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;
Output:
For getting even numbers, we will query the following statement.
select displayevennumbers(11,30);
Output:
Example #4
Iterating an array using foreach.
Code:
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 the function is created successfully, then the CREATE FUNCTION will be displayed after you copy and paste and fire the above function definition. 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 –
Array[[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]];
which in graphical form is as follows –
1 2
3 4
5 6
7 8
9 10
11 12
Now, our calling statement will be
SELECT displayRowValues(Array[[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]);
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.
Output:
Conclusion
The for loop can be used effectively and conveniently as per our necessity to loop around or execute certain statements repetitively. Besides this, even the result set retrieved from a particular query can be iterated using for loop in PostgreSQL.
Recommended Articles
This is a guide to PostgreSQL For Loop. Here we discuss the Introduction to PostgreSQL For Loop and the practical examples and different subquery expressions. You can also go through our suggested articles to learn more –