A VARIADIC
parameter can get an array from the caller.
For example, you use a VARIADIC
parameter in a function as shown below. *A VARIADIC
parameter must be the last parameter otherwise there is the error:
CREATE FUNCTION my_func(VARIADIC nums INTEGER[]) RETURNS INTEGER
AS $$ -- ↑ Here ↑
BEGIN
RETURN nums[1] + nums[2];
END;
$$ LANGUAGE plpgsql;
Or:
CREATE FUNCTION my_func(VARIADIC INTEGER[]) RETURNS INTEGER
AS $$ -- ↑ Here ↑
BEGIN
RETURN $1[1] + $1[2];
END;
$$ LANGUAGE plpgsql;
Then, calling my_func(2, 3)
returns 5
as shown below. You must pass an argument to a VARIADIC
parameter otherwise there is the error:
postgres=# SELECT my_func(2, 3);
my_func
---------
5
(1 row)
postgres=# SELECT my_func(VARIADIC ARRAY[2,3]);
my_func
---------
5
(1 row)
Be careful, calling my_func(ARRAY[2,3])
gets the error as shown below:
postgres=# SELECT my_func(ARRAY[2,3]);
ERROR: function my_func(integer[]) does not exist
LINE 1: SELECT my_func(ARRAY[2,3]);
^
HINT: No function matches the given name and argument types. You might need to add explicit typ
e casts.
And, calling my_func()
gets the error as shown below:
postgres=# SELECT my_func();
ERROR: function my_func() does not exist
LINE 1: SELECT my_func();
^
HINT: No function matches the given name and argument types. You might need to add explicit type
casts.
apple=#