Skip to content

Instantly share code, notes, and snippets.

@stellingsimon
Created August 22, 2019 05:41
Show Gist options
  • Save stellingsimon/e7c6bf20209a3309211f328e606f56d8 to your computer and use it in GitHub Desktop.
Save stellingsimon/e7c6bf20209a3309211f328e606f56d8 to your computer and use it in GitHub Desktop.
Simulation of first_value(x IGNORE NULLS) on Postgres
-- found here: 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