I am trying to make a function in PostgreSQL, which would take a name of a table and a name of one column in that table (in varchars); and return an array which would have minimum and maximum values of that column.
In advance I do not (want to) know the type of the column, ie. type of the elements in the return array.
I've tried to create a function with polymorphic anyarray as a return type, but keep hitting syntax errors. Have tried both in SQL and in PLPQSQL.
CREATE OR REPLACE FUNCTION minmax(tablename character varying, columnname character varying, OUT minmaxa anyarray) AS
$function$
BEGIN
EXECUTE FORMAT('SELECT array_agg(foo) AS %s FROM (
(SELECT min(%s) AS foo FROM %s)
UNION
(SELECT max(%s) AS foo FROM %s)
) AS foobar'
, columnname
, columnname, tablename
, columnname, tablename)
INTO minmaxa;
END
$function$
LANGUAGE plpgsql;
The string from the FORMAT would be:
SELECT array_agg(foo) AS columnname FROM (
(SELECT min(columnname) AS foo FROM tablename)
UNION
(SELECT max(columnname) AS foo FROM tablename)
) AS foobar
Then test case:
create table example (columnA int, columnB varchar);
insert into example (columnA, columnB) values (1, 'ac'), (2, 'ab'), (3, 'aa');
select minmax('example', 'columnA');
select minmax('example', 'columnB');
select array_agg(columnA) from (
(select min(columnA) AS columnA from example)
UNION
(select max(columnA) AS columnA from example)
) AS foobar;
Should return:
{1,3}
{'aa','ac'}
{1,3}
But currently function definition gives: "SQL Error [42P13]: ERROR: cannot determine result data type Detail: A function returning a polymorphic type must have at least one polymorphic argument."
I can make it work, by defining a dummy function parameter 'foo':
CREATE OR REPLACE FUNCTION minmax(tablename character varying, columnname character varying, foo anyelement, OUT minmaxa anyarray)
(Note. A function parameter foo is not used in function body anywhere.)
And now giving a dummy typed value of the correct type of returning array when calling the function:
select minmax('example', 'columnB', ''::varchar);
select minmax('example', 'columnA', 0::int);
Then it works, but what should be changed to I would not need that dummy function parameter?