The difference between COALESCE and NVL

Asked

Viewed 31,808 times

9

In Oracle when we have a table that has two campuses A and B, and in selection (select) we want to show B when A is null we have two commands that present us the solution:

Coalesce

Select COALESCE(A,B) Teste
 from TabelaTeste

NVL

Select NVL(A,B) Teste
     from TabelaTeste

What is the difference between these commands? Are any more performative? What criteria should I use to choose?

  • 3

    Related (about MS-SQL/T-SQL): https://answall.com/q/55733

2 answers

19


The function NVL is specific to Oracle and only accepts two expressions as input.

If the first expression is null, the function will return the second expression. Otherwise, the first expression will be returned.

Input expressions can also be of different types, if this happens, an attempt will be made to cast implicit, if the cast is not possible an error will be returned.

Also, this function always evaluates the two input expressions, making it slightly less performative than the COALESCE.

Illustration of function NVL:

Função NVL.

Documentation image

The COALESCE is part of the pattern ANSI-92, therefore it is a command that exists in all databases that follow this pattern or higher.

It always returns the first non-null value in the expression list. You need to specify at least two expressions, but you can specify more.

Illustration of function COALESCE:

inserir a descrição da imagem aqui

Documentation image

10

The differences are:

  1. COALESCE follows the ANSI standard while NVL is specific to Oracle;
  2. NVL accepts only 2 pointers while COALESCE can receive multiple arguments;
  3. NVL executes both arguments and COALESCE for the first occurrence of a non-zero value;
  4. NVL makes an implicit conversion of the data type based on the first parameter reported, COALESCE expects all parameters to be of the same type;

Example:

select nvl('abc',10) from dual; It will work with implicit conversion from number 10 to string.

select coalesce('abc',10) from dual; It will generate the following error: "Inconsistent datatypes: expected CHAR got NUMBER".

  1. COALESCE has problems in queries using UNION clauses (Example below);

Example:

SELECT COALESCE(a, sysdate) 
from (select null as a from dual 
      union 
      select null as a from dual
      );

It will give the following error: "ORA-00932: inconsistent datatypes: expected CHAR got DATE".

SELECT NVL(a, sysdate) 
from (select null as a from dual 
      union 
      select null as a from dual
      ) ;

Will successfully execute.

Source: Stack Overflow

Browser other questions tagged

You are not signed in. Login or sign up in order to post.