Skip to content
Advertisement

Create new rows based on condition – Oracle SQL

I have a table

  • 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:

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:

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