When I want to test the behavior of some PostgreSQL function FOO() I'd find it useful to execute a query like SELECT FOO(bar), bar being some data I use as a direct input without having to SELECT from a real table.
I read we can omit the FROM clause in a statement like SELECT 1 but I don't know the correct syntax for multiple inputs. I tried SELECT AVG(1, 2) for instance and it does not work.
How can I do that ?
With PostgreSQL you can use a VALUES expression to generate an inlined table:
VALUES computes a row value or set of row values specified by value expressions. It is most commonly used to generate a "constant table" within a larger command, but it can be used on its own.
Emphasis mine. Then you can apply your aggregate function to that "constant table":
select avg(x)
from (
values (1.0), (2.0)
) as t(x)
Or just select expr if expr is not an aggregate function:
select sin(1);
You could also define your own avg function that operates on an array and hide your FROM inside the function:
create function avg(double precision[]) returns double precision as $$
select avg(x) from unnest($1) as t(x);
$$ language 'sql';
And then:
=> select avg(array[1.0, 2.0, 3.0, 4.0]);
avg
-----
2.5
But that's just getting silly unless you're doing this quite often.
Also, if you're using 8.4+, you can write variadic functions and do away with the array. The internals are the same as the array version, you just add variadic to the argument list:
create function avg(variadic double precision[]) returns double precision as $$
select avg(x) from unnest($1) as t(x);
$$ language 'sql';
And then call it without the array stuff:
=> select avg(1.0, 1.2, 2.18, 11, 3.1415927);
avg
------------
3.70431854
(1 row)
Thanks to depesz for the round-about-through-google pointer to variadic function support in PostgreSQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With