Skip to content
Advertisement

Create new rows based on condition – Oracle SQL

I have a table

ID ID2 VARIABLE   VA_VAL

1 100  F_NAME     ABC
1 102  QUAL       01
1 103  CODE       1923

2 100  F_NAME     BCD
2 102  QUAL       02
2 103  CODE       2034

3 100  F_NAME     CDE
3 102  QUAL       01
3 103  CODE       5436
  • If ID2 = 102 and VARIABLE = QUAL and VA_VAL = 01, then insert ID2 = 104, VARIABLE = NEW_CD1 and VA_VAL = (VA_VAL of (ID2 = 103 and VARIABLE = CODE) )

    Also, delete rows (ID2 = 102 and VARIABLE = QUAL and VA_VAL = 02) and (ID2 = 103 and VARIABLE = CODE) for the same ID.

  • If ID2 = 102 and VARIABLE = QUAL and VA_VAL = 02, then insert ID2 = 103, VARIABLE = NEW_CD2 and VA_VAL = (VA_VAL of (ID2 = 103 and VARIABLE = CODE) )

    Also, delete rows (ID2 = 102 and VARIABLE = QUAL and VA_VAL = 02) and (ID2 = 103 and VARIABLE = CODE) for the same ID.

The output table would be like:

ID ID2 VARIABLE    VA_VAL

1 100  F_NAME      ABC
1 104  NEW_CD1     1923

2 100  F_NAME      BCD
2 105  NEW_CD2     2034

3 100  F_NAME      CDE
3 104  NEW_CD1     5436

Is there a way to do it in Oracle SQL which is efficient? I have more than 50 million records in the table.

Advertisement

Answer

I assume you just want a result set. Here is the idea:

  1. Select the existing rows that you do want.
  2. Add in each variable as a separate subquery.

The resulting query looks like:

select ID, ID2, VARIABLE, VA_VAL
from t
where not ((ID2 = 102 and VARIABLE = 'QUAL' and VA_VAL = '02') or
           (ID2 = 103 and VARIABLE = 'CODE')
          ) 
union all
select t.id, 104 as id2, 'NEW_CD1',
       max(case when ID2 = 103 and VARIABLE = 'CODE' then VA_VAL end)
from t
group by t.id
having max(case when ID2 = 103 and VARIABLE = 'CODE' then VA_VAL end) is not null
union all
select t.id, 104 as id2, 'NEW_CD1',
       max(case when ID2 = 102 and VARIABLE = 'QUAL' then VA_VAL end
from t
group by t.id
having max(case when ID2 = 102 and VARIABLE = 'QUAL' then VA_VAL end) is not null;

If you want to replace your existing table — and there are lots of changes (which I assume is true) — run this query and save the results in a table.

Then, truncate the existing table and re-insert the values into it.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement