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:
Emphasis mine. Then you can apply your aggregate function to that “constant table”:
Or just
select exprifexpris not an aggregate function:You could also define your own
avgfunction that operates on an array and hide your FROM inside the function:And then:
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
variadicto the argument list:And then call it without the array stuff:
Thanks to depesz for the round-about-through-google pointer to variadic function support in PostgreSQL.