1

I am able to do the following in SQL where an "array" of user_ids are passed into the where clause of a SQL query.

select * from users where id in (select user_id from profiles);

I would like to do the same thing but pass the "array" into a PostgreSQL (PL/pgSQL) function as shown below. How do I declare the function and work with the "array" within the function?

select * from users_function(select user_id from profiles);

CREATE OR REPLACE FUNCTION users_function(....)
  RETURNS void AS
$BODY$
....

2 Answers 2

2

Declare an array datatype [] in the function then use the aggregate function array_agg to transform the select statement into an array.

CREATE OR REPLACE FUNCTION users_function(myints integer[])
$$
 BEGIN
      -- you need to find the bounds with array_lower and array_upper
  FOR i in array_lower(myints, 1) .. array_upper(myints, 1) LOOP
     Raise Notice '%', myints[i]::integer;
  END LOOP;
 END;
$$

select * from users_function(array_agg((select user_id from profiles)));
Sign up to request clarification or add additional context in comments.

3 Comments

I'm running PostgreSQL 8.4.4 and getting this error. Any ideas? select array_agg(select id from users limit 2); ERROR: syntax error at or near "select"
Add another set of brackets like: select array_agg((select id from users limit 2)). Forgot that - any time you have a subquery in a function you need two sets: one for the function an one for the subquery.
Sorry to keep bothering you, but this is what I got: select array_agg((select id from users limit 2)); ERROR: more than one row returned by a subquery used as an expression
1

I could not get the nate c's array_agg approach as I described above. This is an option:

select * from test_array('{1,2}');

CREATE OR REPLACE FUNCTION test_array(user_ids integer[])
  RETURNS void AS
$$
declare
begin
FOR i in array_lower(user_ids, 1) .. array_upper(user_ids, 1) LOOP
  RAISE NOTICE '%', user_ids[i]::integer;
END LOOP;
end
$$
LANGUAGE plpgsql;

Comments

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.