While looking for an aggregate function that returns the nth element of a collection I found the following solution:
CREATE OR REPLACE FUNCTION _final_nth( anyarray, integer )
RETURNS anyelement AS
$BODY$
SELECT a
FROM unnest( $1 ) a
ORDER BY a
offset $2
LIMIT 1;
$BODY$
LANGUAGE 'sql' IMMUTABLE;
CREATE AGGREGATE nth( anyelement, integer ) (
SFUNC=array_append,
STYPE=anyarray,
FINALFUNC=_final_nth,
INITCOND='{}'
);
Creating the function works fine but executing CREATE AGGREGATE produces the following error:
ERROR: function array_append(anyarray, anyelement, integer) does not exist
I am not able to resolve this error.
OFFSET/LIMIT, and if it's an array, what's wrong with a straightmyarray[n]? Why do you need an aggregate at all? Also, the error looks pretty obvious to me. PostgreSQL is trying to pass the current state plus the aggregate's arguments to theSFUNC, and there's noarray_appendthat takes those arguments (nor would it make any sense for there to be).