Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select statement inside NVL

Tags:

oracle

nvl

I'm trying to run the following query:

select a.*, 
    case when NVL (SELECT max(b.field1)
        FROM b
        where b.field2 = a.tbl_a_PK , 'TRUE') = 'TRUE' 
            then 'has no data in b'
            else 'has data in b' end as b_status
from a

I checked and the select inside the nvl returns only 1 value (so there shouldn't be a problem there). However I'm getting 'ORA-00936: missing expression'

like image 723
Naama Zrihen Avatar asked May 22 '13 15:05

Naama Zrihen


People also ask

Can we use NVL inside NVL?

A subquery can not be used inside a NVL.

What is NVL () in SQL?

NVL(expr1, expr2) : In SQL, NVL() converts a null value to an actual value. Data types that can be used are date, character and number.

Can we use NVL in Join condition?

You can use a LEFT JOIN . That will return all rows from tableOne , and when it can't find a match in the second table, it will return null. Then you can use NVL like you mentioned. If you're expecting nulls from equip_pk , you can apply NVL to that to.


1 Answers

NVL() requires 2 parameters: expression to test and default value e.g. nvl(some_field, 111). You just need to isolate query parameter by braces and provide second parameter like in this statement:

select nvl( (select 1 from dual), 34) from dual 

In your variant parser expects comma after SELECT keyword and can't parse remaining string.

Exactly your statement must look like this:

select 
  a.*, 
  case when NVL(
              ( SELECT max(b.field1)
                FROM b
                where b.field2 = a.tbl_a_PK
              ), 
              'TRUE'
            ) = 'TRUE' 
       then 'has no data in b'
       else 'has data in b' end                  as b_status
from a

Hope this helps ...

Update In terms of performance is better to use exists rather then max :

select 
  a.*, 
  case when exists
              ( SELECT null
                FROM b
                where b.field2 = a.tbl_a_PK 
                      and 
                      b.field2 is not null
                      and 
                      rownum = 1
              ), 
       then 'has data in b'
       else 'has no data in b' end                  as b_status
from a
like image 139
ThinkJet Avatar answered Sep 23 '22 23:09

ThinkJet