Fun with UPDATE Statement


Imagine a Scenario with 2 Tables: (T_UNIT and T_COGENT)

SQL > desc T_UNIT
 Name                          Null?    Type
 ----------------------------- -------- --------------------
 UNIT_ID                       NOT NULL NUMBER
 COGENT_ID                              NUMBER

SQL > desc T_COGENT
 Name                          Null?    Type
 ----------------------------- -------- --------------------
 UNIT_ID                       NOT NULL NUMBER
 COGENT_ID                              NUMBER


SQL >


The below UPDATE statement will update T_UNIT.unit_id column with the value from T_COGENT.unit_id with matching cogent_id. We will use a sub-query in the SET clause to compare the two tables.

UPDATE T_UNIT a
   SET a.unit_id = (SELECT b.unit_id from T_COGENT b WHERE a.cogent_id = b.cogent_id);



Ex :

SQL > select * from T_UNIT;

   UNIT_ID  COGENT_ID
---------- ----------
         1        101
         2        102
         3        103
         4        104
         5        105

SQL > select * from T_COGENT;

   UNIT_ID  COGENT_ID
---------- ----------
        11        101
        22        102
        33        103
        44        104
        55        105

SQL > UPDATE T_UNIT a
   SET a.unit_id = (SELECT b.unit_id from T_COGENT b WHERE a.cogent_id = b.cogent_id);  2

5 rows updated.

SQL > select * from T_UNIT;

   UNIT_ID  COGENT_ID
---------- ----------
        11        101
        22        102
        33        103
        44        104
        55        105

SQL >

No comments:

Post a Comment

ASM and Database does not auto start in Oracle restart environment (After Server start)

 If you are supporting Any Oracle restart environment and if you notice that your ASM instance and Database instance does not start automati...