Created
July 5, 2018 08:44
-
-
Save joshlk/81b9a3b113f86a32268037012b908941 to your computer and use it in GitHub Desktop.
User-defined aggregate/window function that selects the first non-null element (Postgres SQL)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- https://wiki.postgresql.org/wiki/First/last_(aggregate) | |
-- Create a function that always returns the first non-NULL item | |
CREATE OR REPLACE FUNCTION public.first_agg ( anyelement, anyelement ) | |
RETURNS anyelement LANGUAGE SQL IMMUTABLE STRICT AS $$ | |
SELECT $1; | |
$$; | |
-- And then wrap an aggregate around it | |
CREATE AGGREGATE public.FIRST ( | |
sfunc = public.first_agg, | |
basetype = anyelement, | |
stype = anyelement | |
); | |
-- Create a function that always returns the last non-NULL item | |
CREATE OR REPLACE FUNCTION public.last_agg ( anyelement, anyelement ) | |
RETURNS anyelement LANGUAGE SQL IMMUTABLE STRICT AS $$ | |
SELECT $2; | |
$$; | |
-- And then wrap an aggregate around it | |
CREATE AGGREGATE public.LAST ( | |
sfunc = public.last_agg, | |
basetype = anyelement, | |
stype = anyelement | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment