Rewrite plpgsql function to sql
Is it possible to rewrite the following plpgsql function as a sql function? I'm using it to aggregate my data by most recent timestamp, but wish to deploy on heroku which doesn't support plpgsql. I could totally rewrite my original query that uses this function, but I'd like to keep the flexibility for being able to drop in other aggregate functions.
CREATE OR REPLACE FUNCTION recent_accum(anyelement, anyelement) RETURNS anyelement AS $$ BEGIN IF $1.tstamp IS NULL and $2.tstamp IS NOT NULL THEN RETURN $2; ELSEIF $1.tstamp IS NOT NULL and $2.tstamp IS NULL THEN RETURN $1; ELSEIF $2.tstamp > $1.tstamp THEN RETURN $2; ELSE RETURN $1; END IF; END; $$ LANGUAGE plpgsql;
Does it work to rewrite the IF/ELSEIF chain using CASE?
CASE WHEN $1.tstamp IS NULL AND $2.tstamp IS NOT NULL THEN $2 -- ... ELSE $1 END