Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. SQL Server
  3. Question
SQL Server

What is the function of postgresql nvl?

Asked by Dan Peters Sep 29, 2022 2.4K views 1 answer
Share

About this question

 I'm trying to have an 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...


Your answer

1 Answer

More SQL Server discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest SQL Server Blogs

Guides, tips and career advice on SQL Server from JanBask experts.