Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing a number in a loop in plpgsql

I couldn't find this immediately from the examples. I want to increment a variable in a loop, in a function.

For instance:

DECLARE
   iterator float4;
BEGIN
   iterator = 1;

    while iterator < 999
       .....
      iterator ++;
END;

How would this be done?

I was looking at this document about flow control:
http://www.postgresql.org/docs/8.4/static/plpgsql-control-structures.html

And none of them seem to be relevant for me, unless these are absolutely the only ways to simulate incrementing a variable.

like image 439
CQM Avatar asked Dec 07 '12 20:12

CQM


People also ask

Is there auto increment in PostgreSQL?

By simply setting our id column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our id column with a unique, primary key value for every INSERT .

Does a FOR loop automatically increment?

A for loop doesn't increment anything. Your code used in the for statement does.

How do I loop a record in PostgreSQL?

Using a different type of FOR loop, you can iterate through the results of a query and manipulate that data accordingly. The syntax is: [ << label >> ] FOR target IN query LOOP statements END LOOP [ label ]; The target is a record variable, row variable, or comma-separated list of scalar variables.

Can you do a loop in PostgreSQL?

Postgresql supports For loop statements to iterate through a range of integers or results from a sequence query. The For loop is used to iterate over a set of numbers or objects.


2 Answers

For a sscce

DO $$
DECLARE
   counter INTEGER := 0 ; 
BEGIN
   WHILE counter <= 5 LOOP
      counter := counter + 1 ; 
      RAISE NOTICE 'Counter: %', counter;
   END LOOP ; 
END; $$

if you want to avoid declare variable (more concise)

DO $$
BEGIN
   FOR counter IN 1..5 LOOP
      RAISE NOTICE 'Counter: %', counter;
   END LOOP;
END; $$

credits

like image 82
albfan Avatar answered Sep 25 '22 13:09

albfan


To increment a variable in plpgsql:

iterator := iterator + 1;

There is no ++ operator.

About the assignment operator in plpgsql:

  • The forgotten assignment operator "=" and the commonplace ":="

Correct syntax for loops in PL/pgSQL in the manual.

Your code fragment would work like this:

DECLARE
   iterator float4 := 1;  -- we can init at declaration time
BEGIN
   WHILE iterator < 999
   LOOP
      iterator := iterator + 1;
      -- do stuff
   END LOOP;
END;

Simpler, faster alternative with a FOR loop:

   FOR i in 1 .. 999   -- i is integer automatically, not float4
   LOOP
      -- do stuff
   END LOOP;

The manual:

The variable name is automatically defined as type integer and exists only inside the loop (any existing definition of the variable name is ignored within the loop).

like image 32
Erwin Brandstetter Avatar answered Sep 26 '22 13:09

Erwin Brandstetter