0

I have a postgres DB and I want to create a function that returns a copy of my table with a new column that has a value of 1 if its id is inside the array(idds[]) that the function gets as an input. In the code below I've try to create a temporary table(chosen) that have id if it's in the idds array and to manually add the isChosen column that obviously doesn't work...

CREATE OR REPLACE FUNCTION public.getTableFromArray(idds integer[])
    RETURNS table(
id INTEGER,
isChosen INTEGER
)
    LANGUAGE 'plpgsql'
    
AS $BODY$


begin
with chosen AS(SELECT id,isChosen=1 FROM table1 WHERE ARRAY[table1.id] <@ idds)
return query
SELECT id FROM table1 LEFT JOIN chosen ON table1.id=chosen.id;

end;
$BODY$;

2 Answers 2

1

Or, with a lot less noise, a proper boolean output column, and without the unhelpful CaMeL case identifiers in a plain SQL function:

CREATE OR REPLACE FUNCTION public.get_table_from_array(idds integer[])
  RETURNS TABLE(id int, is_chosen bool)
  LANGUAGE sql AS
'SELECT t.id, t.id = ANY(idds) FROM table1 t';

Might as well just run the SQL command directly, though:

SELECT id, id = ANY('{1,2,3}'::int[]) AS is_chosen FROM table1;
Sign up to request clarification or add additional context in comments.

Comments

0

you can use this query instead :

select * , case when ARRAY[table1.id] <@ idds then 1 else 0 end as choosen FROM table1;

so:

CREATE OR REPLACE FUNCTION public.getTableFromArray(idds integer[])
    RETURNS table(
id INTEGER,
isChosen INTEGER
)
    LANGUAGE 'plpgsql'    
AS $BODY$
begin
return query
select id , case when ARRAY[table1.id] <@ idds then 1 else 0 end as isChosen FROM table1;
end;
$BODY$;

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.