Search code examples
oracle-databaseplsqlsql-updatecorrelated-subquery

How to update a table based on the values in another table?


I am trying to update a column in one table with the values contained in the column from another table. I've tried the following but it gives me an error saying it returns more than one row.

update Table1 set description1 = (select description2 from Table2)
where customer_id in (select customer_id from Table2);    

Any guidance?


Solution

  • To do a correlated update, your subquery has to return a single row. Almost always, you do this by correlating the key that tells you which row from table2 maps to which row from table1. Assuming that both tables have a column named key that is unique

    UPDATE table1 t1
       SET description = (SELECT t2.description2
                            FROM table2 t2
                           WHERE t1.key = t2.key)
     WHERE t1.customer_id IN (SELECT t2.customer_id
                                FROM table2)