Search code examples
oracle-databaseisnull

merge 2 Oracle queries into one with some generic data specified with null


Can I write one Oracle query that can do something like that? if code is XXX, then return V1,V2 if code is not XXX, then return those values whose code = null, i.e. V3, V4

Table1

code value
---- -----
XXX V1
XXX V2
null    V3
null    V4

I need to write something like that:

  • select * from Table1 where code = 'XXX'
  • if no rows return, run the follow query
  • select * from Table1 where code is null

Solution

  • I'm not sure that I completely follow what you are looking for. You could implement your bullet points with something like

    select *
      from table1 t1
     where t1.code = 'XXX'
    union all
    select *
      from table1 t1_2
     where t1_2.code is null
       and not exists( select 1
                         from table1 t1_3
                        where t1_3.code = 'XXX' )