I created a function that returns all values that meet the condition specified and tried specifying int[]
as the result type of the function.
create or replace function mults_of_3_5(id int) returns int[] language sql as
$$
SELECT ValuesUnder1000
FROM Mults
WHERE (ValuesUnder1000 % 3 = 0) or (ValuesUnder1000 % 5 = 0);
$$;
I got the error
ERROR: return type mismatch in function declared to return integer[]
DETAIL: Actual return type is integer.
CONTEXT: sql function "mults_of_3_5"
The data type of ValuesUnder1000
is integer
.
When I use the same query outside the function, all the values in the column that satisfies the condition are listed.
Please tell me what I can do to return an array in PostgreSQL.
2
Answers
Use
pg_typeof
to check your data types:Your function
returns setof int
. If you want it to return anint[]
array instead, you need to assemble that array.array_agg()
can helpIt’s also possible to use
returns table (valuesunder1000 int)
. Refer to the manual for details on how to build functions.You can also use a set-returning function (SRF):
I tested it as follows and it seems it works: