Home > Back-end >  Possible to pass multiple inline values to an aggregation function?
Possible to pass multiple inline values to an aggregation function?

Time:05-11

I can call an aggregation function directly on a scalar literal value, such as:

select SUM(2);
┌────────┐
│ sum(2) │
╞════════╡
│      2 │
└────────┘
Elapsed: 1 ms

Is there any way to pass multiple inline values into an aggregation function, such as:

SELECT SUM(1,2,3) 
SELECT SUM([1,2,3])
SELECT SUM((1,2,3))
etc.

I know I can do this with a CTE or a VALUES clause or something else in the FROM, but I'm wondering if it can be used directly without a FROM clause. Actual DB doesn't matter here.

CodePudding user response:

You can define a function with variadic to pass multiple parameters. In the background such an argument is an array.

create function my_sum(variadic p_numbers integer[])
  returns bigint
as
$$
  select sum(i)
  from unnest(p_numbers) as u(i);
$$
language sql
stable;

You can then call it using

select my_sum(1,2,3);
select my_sum(2,7);
  • Related