1

I have this snippet of code:

RAISE NOTICE 'p_new_roster: %', p_new_roster; --prints {3,4,5}
FOREACH i IN ARRAY p_new_roster
LOOP
  RAISE NOTICE 'p_new_roster[i]: %', p_new_roster[i]; --prints 5,NULL,NULL (through 3 iterations)
  v_new_users := v_new_users || p_new_roster[i];
END LOOP;

How come p_new_roster[1] is 5, p_new_roster[2] is NULL, etc.? Variable i is declared as integer, and arrays are declared as integer[].

Basically what I am trying to do is clone 'p_new_roster' array. If somebody knows better way, I would like to know how too.

5
  • 1
    PostgreSQL arrays are immutable. Why would you "clone" it? Just v_new_users = p_new_roster. What's the actual problem you're trying to solve by doing this, the "why" for the "how" you're asking here? Commented May 15, 2014 at 12:54
  • I have two arrays: arr1 = {1,2,3} and arr2 = {3,4,5} (this is just example). I need function that compares these two arrays and returns in one column {1,2} and in second {4,5} (I would put the result in composite type). Commented May 15, 2014 at 13:08
  • If I do v_new_users := p_new_roster then changes that I do with v_new_users would be seen in p_new_roster also? I need p_new_roster for later use. Commented May 15, 2014 at 13:10
  • @anagarD No. You assign the value of p_new to v_new not a reference to p_new Commented May 15, 2014 at 13:15
  • No, you've completely misunderstood how arrays work in PostgreSQL. They're immutable. It's not like Java where assigning the array just assigns the reference. The whole array is copied. It's like a string in Java. You can't modify an array in-place by setting attributes. Commented May 15, 2014 at 13:33

1 Answer 1

1

If you are trying to take the nulls out of the array do

v_new_users := v_new_users || array_remove(p_new_roster, null)

without the loop

Or just append

v_new_users := v_new_users || p_new_roster

also without the loop

Or your script fixed

RAISE NOTICE 'p_new_roster: %', p_new_roster; --prints {3,4,5}
FOREACH i IN ARRAY p_new_roster
LOOP
  RAISE NOTICE 'p_new_roster[i]: %', i; 
  v_new_users := v_new_users || i;
END LOOP;

i is the array element value at each iteration not the array index

Sign up to request clarification or add additional context in comments.

1 Comment

I tought i was index -.- Thanks your answer helped a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.