I'm trying to have NVL function in postgres.
create or replace function nvl (anyelement, anyelement)
returns anyelement language sql as $$
select coalesce(cast( $1 as decimal), cast( $2 as decimal))
$$;
however this fails on me for the following examples:
testdb=> select nvl(1,2);
ERROR: return type mismatch in function declared to return integer
DETAIL: Actual return type is numeric.
CONTEXT: SQL function "nvl" during inlining
testdb=> SELECT nvl( sum(balance), 0 ) as b FROM db.bank WHERE user = 123;
ERROR: function nvl(numeric, integer) does not exist
LINE 1: SELECT nvl( sum(balance), 0 ) as b FROM db.bank...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
When I change it to:
create or replace function nvl (anyelement, anyelement)
returns anyelement language sql as $$
select case when $1 is null then $2 else $1 END
$$;
The first example works. But I still have failures with:
testdb=> SELECT nvl( sum(balance), 0 ) as b FROM db.bank WHERE user = 123;
ERROR: function nvl(numeric, integer) does not exist
LINE 1: SELECT nvl( sum(balance), 0 ) as b FROM db.bank...
Would love some help fixing this.