Question

Given this:

   with data_row as  (select 1 as col_1 from dual)
   select 'Y' as row_exists from dual where exists 
   (select null 
       from data_row
      where col_1 in (2,1))

How can I get this?

Col_1  Row_exists
--------------------
1       Y
2       N
Was it helpful?

Solution

In order to get a row of output, you need a row of input. You want to get the second row with a "2", but there is no table with that value.

The approach is to generate a table that has the values that you want, and then use left outer join to find which match:

with data_row as (
     select 1 as col_1
     from dual
    ),
    what_i_care_about as (
     select 1 as col from dual union all
     select 2 from dual
    )
select wica.col,
      (case when dr.col_1 is NULL then 'N' else 'Y' end) as row_exists
from what_i_care_about wica left outer join
     data_row dr
     on wica.col = dr.col_1;

You cannot do directly what you want -- which is to create a row for each missing value in the in list. If you have a lot of values and they are consecutive numeric, then you can use connect by or a recursive CTE to generate the values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top