Sam
Sam

Reputation: 2605

Using a variable in the IN clause of a postgresql query

I am very new to postgres. I'd like to accomplish a simple task.

I have a function as below:

create or replace function function1(source json)     
returns json as $$
DECLARE
    output_data json;
begin
    raise notice '%',source::text;
    select json_agg(name_id) into output_data from table1 where channel_id in SOURCE;   -- I want to use SOURCE as dynamic
    return output_data;
end;
$$ LANGUAGE plpgsql;

The function takes input a json parameter (source) and I want to run the IN clause using the parameter.

For example, When I run the below:

select function1('[5555558,5555559]'); 

I should get an output like [11111,22222] ---> these are the name_id

One way to accomplish this task is to insert all the values of SOURCE into a table (new_table) and then do the following.

select json_agg(name_id) into output_data from table1 where channel_id in (select channel_id from new_table);

I would like to know of other better techniques, such as using equivalent of collection or dynamic queries.

thank you

Upvotes: 1

Views: 733

Answers (1)

Patrick
Patrick

Reputation: 32199

In principle this can be done with a single SQL statement:

SELECT json_agg(t.name_id)
FROM table1 t
JOIN json_array_elements_text('[5555558,5555559]'::json) j(value)
  ON j.value = t.channel_id::text;

If you want a function then it is simply:

CREATE FUNCTION function1 (source json) RETURNS SETOF json AS $$
  SELECT json_agg(t.name_id)
  FROM table1 t
  JOIN json_array_elements_text(source) j(value) ON j.value = t.channel_id::text;
$$ LANGUAGE sql;

Upvotes: 1

Related Questions