Skip to content
Advertisement

SQL fill empty values in a column based on case when selection

So basically what I want to achieve is that if four columns are empty, one column contains a 1 as value and one column contains 0, then I want to entries in one column meeting the conditions with a default value (0.06077).

Meaning: IF COL_A, COL_B, COL_C, COL_D IS NULL and COL_E = 0 AND COL_F = 0 then fill the rows in COL_A which meet these conditions with a default value of 0.06077.

I tried the following:

, CASE WHEN COL_A IS NULL AND COL_B IS NULL AND COL_C IS NULL AND COL_D IS NULL 
AND COL_E = 0 AND COL_F = 1 THEN NVL(COL_A, 0.06077) END 

The following did fill the entries meeting my set conditions. Anyone knows a potential sollution?

Advertisement

Answer

IF COL_A, COL_B, COL_C, COL_D IS NULL and COL_E = 0 AND COL_F = 0 then fill the rows in COL_A which meet these conditions with a default value of 0.06077.

You probably needs this case expression:

case when
  coalesce(COL_A, COL_B, COL_C, COL_D) is null and COL_E = 0 AND COL_F = 1 
  then  0.06077
  else COL_A end as COL_A

Example

with dt as (
select null COL_A, null COL_B, null COL_C, null COL_D, 0 COL_E, 1 COL_F from dual union all
select 1 COL_A, null COL_B, null COL_C, null COL_D, 0 COL_E, 1 COL_F from dual union all
select null COL_A, null COL_B, null COL_C, null COL_D, 0 COL_E, 0 COL_F from dual
)
select 
case when
  coalesce(COL_A, COL_B, COL_C, COL_D) is null and COL_E = 0 AND COL_F = 1 
  then  0.06077
  else COL_A end as COL_A, 
COL_B, COL_C, COL_D, COL_E, COL_F
from dt;

     COL_A COL_B COL_C COL_D      COL_E      COL_F
---------- ----- ----- ----- ---------- ----------
,06077                                0          1
         1                            0          1
                                      0          0
Advertisement