Question

I would like to create a function on postgresql that receives an array of bigint (record ids) and to use the received information on a query using the "in" condition.

I know that I could simply fo the query by my self, but the point over here is that I'm going to create that function that will do some other validations and processes.

The source that I was tring to use was something like this:

CREATE OR REPLACE FUNCTION func_test(VARIADIC arr bigint[])
RETURNS TABLE(record_id bigint,parent_id bigint)
AS $$ SELECT s.record_id, s.parent_id FROM TABLE s WHERE s.column in ($1);
$$ LANGUAGE SQL;

Using the above code I receive the following error:

ERROR:  operator does not exist: bigint = bigint[]
LINE 3: ...ECT s.record_id, s.parent_id FROM TABLE s WHERE s.column in ($1)
                                                                    ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

How can I fix this?

Was it helpful?

Solution

IN doesn't work with arrays the way you think it does. IN wants to see either a list of values

expression IN (value [, ...])

or a subquery:

expression IN (subquery)

A single array will satisfy the first one but that form of IN will compare expression against each value using the equality operator (=); but, as the error message tells you, there is no equality operator that can compare a bigint with a bigint[].

You're looking for ANY:

9.23.3. ANY/SOME (array)

expression operator ANY (array expression)
expression operator SOME (array expression)

The right-hand side is a parenthesized expression, which must yield an array value. The left-hand expression is evaluated and compared to each element of the array using the given operator, which must yield a Boolean result. The result of ANY is "true" if any true result is obtained. The result is "false" if no true result is found (including the case where the array has zero elements).

So you want to say:

WHERE s.column = any ($1)

Also, you're not using the argument's name so you don't need to give it one, just this:

CREATE OR REPLACE FUNCTION func_test(VARIADIC bigint[]) ...

will be sufficient. You can leave the name there if you want, it won't hurt anything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top