Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array in postgres inside a loop

I am trying to initialize an array array_entries. Tries array_fill as array_fill(0,array_entries) but dint work.

create or replace function vin_temp_test1(k date,x varchar) RETURNS float AS $$
    declare
    array_entries int [];
    curs4  CURSOR FOR  select * from temp_table;
    record_type1 record;

    fetch curs4 into record_type1;
            exit when not found;
    loop
    -- trying to intialize the array array_entries here
        loop
     --filling the array inside this loop.
        end loop;
    end loop;
like image 902
user2569524 Avatar asked Jun 06 '26 02:06

user2569524


1 Answers

Probably you have NULL in array_entries

postgres=# select array_fill(0, NULL);
ERROR:  dimension array or low bound array cannot be null
postgres=# select array_fill(0, ARRAY[10]);
      array_fill       
-----------------------
{0,0,0,0,0,0,0,0,0,0}
(1 row)

Attention!

Is good to know, so update of large array (larger than 20000 fields) is pretty slow. So much faster than repeatable update is using ARRAY(subselect) constructor

postgres=# DO $$ DECLARE x int[]; 
           begin  
              x := array_fill(0,ARRAY[100000]); 
              for i in 1..100000 loop 
                x[i] := 1; 
           end loop; end $$;
DO
Time: 5533.581 ms
postgres=# DO $$ DECLARE x int[]; 
           begin  x := ARRAY(SELECT 1 FROM generate_series(1,100000)); end $$;
DO
Time: 36.590 ms
like image 71
Pavel Stehule Avatar answered Jun 07 '26 22:06

Pavel Stehule



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!