Fill rows in column A with value of column B if condition in column A is met

1.3k views Asked by At

I have a table like:

colA    | colB
" "     | 1
"K 111" | 1
"K222"  | 2
" "     | 3

Some columns have only a space (" "), some have "K {number}", some have "K{number}".

If colA has only a space I want that value replaced with the one from colB.

So endresult should be:

colA    | colB
1       | 1
"K 111" | 1
"K222"  | 2
3       | 3

How can I do this?

4

There are 4 answers

1
Gordon Linoff On BEST ANSWER

You can use a case expression:

select (case when colA = ' ' then to_char(col_b)
             else colA
        end) as new_colA

If you wanted to be more general, you might use like:

select (case when colA like 'K%' then colA
             else
        end) as new_colA

In an update, you would move the when condition to a filtering condition:

update t
    set colA = to_char(colb)
    where colA = ' ';
2
Littlefoot On

Or, DECODE function (just an alternative to CASE):

SQL> with test (cola, colb) as
  2    (select 'K 111', 1 from dual union all
  3     select ' '    , 1 from dual union all
  4     select 'K222' , 2 from dual union all
  5     select ' '    , 3 from dual
  6    )
  7  select decode(cola, ' ', to_char(colb), cola) cola,
  8         colb
  9  from test;

COLA             COLB
---------- ----------
K 111               1
1                   1
K222                2
3                   3

SQL>
0
Popeye On

Yet another option is to update the value using IS NULL check as follows:

update your_table
   set colA = to_char(colB)
 where trim(colA) is null;

Empty string in Oracle is considered as null.

0
GMB On

You can use a case expression:

select 
    case when cola = ' ' then to_char(colb) else cola end as cola,
    colb
from mytable

Note that all branches of a case expression must return values of the same datatype. It seems like colb is a number, so this converts it to a string.