Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NVL for multiple columns - Oracle SQL

Good morning my beloved sql wizards and sorcerers,

I am wanting to substitute on 3 columns of data across 3 tables. Currently I am using the NVL function, however that is restricted to two columns.

See below for an example:

    SELECT ccc.case_id,
           NVL (ccvl.descr, ccc.char)) char_val

               FROM case_char ccc, char_value ccvl, lookup_value lval1
              WHERE   
                    ccvl.descr(+) = ccc.value
                    AND ccc.value = lval1.descr (+)
                    AND ccc.case_id IN ('123'))



     case_char table
     case_id|char |value
       123  |email| work_email
       124  |issue| tim_ 



     char_value table
     char  | descr
work_email | complaint mail
    tim_   | timeliness


    lookup_value table
    descr  | descrlong
 work_email| [email protected]

Essentially what I am trying to do is if there exists a match for case_char.value with lookup_value.descr then display it, if not, then if there exists a match with case_char.value and char_value.char then display it.

I am just trying to return the description for 'issue'from the char_value table, but for 'email' I want to return the descrlong from the lookup_value table (all under the same alias 'char_val').

So my question is, how do I achieve this keeping in mind that I want them to appear under the same alias.

Let me know if you require any further information.

Thanks guys

like image 970
Heisenberg Avatar asked Jul 01 '14 03:07

Heisenberg


People also ask

Can NVL have 3 parameters?

The Oracle NVL2() function accepts three arguments.

How do I use NVL in Oracle?

The Oracle NVL() function allows you to replace null with a more meaningful alternative in the results of a query. The NVL() function accepts two arguments. If e1 evaluates to null, then NVL() function returns e2 . If e1 evaluates to non-null, the NVL() function returns e1 .

Is NVL better than coalesce?

NVL and COALESCE are used to achieve the same functionality of providing a default value in case the column returns a NULL. The differences are: NVL accepts only 2 arguments whereas COALESCE can take multiple arguments. NVL evaluates both the arguments and COALESCE stops at first occurrence of a non-Null value.

How many arguments can NVL have?

The NVL function accepts two arguments: the first argument takes the name of the expression to be evaluated; the second argument specifies the value that the function returns when the first argument evaluates to NULL.


2 Answers

You could nest NVL:

 NVL(a, NVL(b, NVL(c, d))

But even better, use the SQL-standard COALESCE, which does take multiple arguments and also works on non-Oracle systems:

COALESCE(a, b, c, d)
like image 76
Thilo Avatar answered Sep 22 '22 18:09

Thilo


How about using COALESCE:

COALESCE(ccvl.descr, ccc.char)
like image 34
Linger Avatar answered Sep 22 '22 18:09

Linger