First (aggregate)
From PostgreSQL wiki
Library Snippets
First (aggregate)
Works with PostgreSQL
Any version
Written in
SQL
Depends on
Nothing
This aggregate function returns the value from the first input row in each group.
See also: Last (aggregate)
Portable SQL version
This is a portable SQL-language implementation with no external dependencies.
-- Create a function that always returns the first non-NULL item CREATE OR REPLACE FUNCTION public.first_agg ( anyelement, anyelement ) RETURNS anyelement AS $$ SELECT $1; $$ LANGUAGE SQL IMMUTABLE STRICT; -- And then wrap an aggreagate around it CREATE AGGREGATE public.first ( sfunc = public.first_agg, basetype = anyelement, stype = anyelement );
Credit: http://archives.postgresql.org/pgsql-hackers/2006-03/msg01324.php with a couple of corrections.
Fast C version
A faster version written in C is avaiblable in PGXN, called first_last_agg: http://pgxn.org/dist/first_last_agg/
