0

I have the following table:

table1
company_id   |    description        | 
-------------------------------------
1            |  old description1     |
2            |  old description2     |
3            |  old description3     |
4            |  old description4     |

I want to update the descriptions with table2 where the company id's are equal.

table2
company_id   |    description        | 
-------------------------------------
1            |  NEW description1     |
3            |  NEW description2     |

so that the final table is

table1
company_id   |    description        | 
-------------------------------------
1            |  NEW description1     |
2            |  old description2     |
3            |  NEW description3     |
4            |  old description4     |

My code I'm using is

update table1
set table1.description = (
select table2.description from table2 where table2.company_id=table1.company_id);

The issue is that when I run this update, the descriptions of companies who's id's are not in table2 get turned to null. How do I write it so that it keeps all the other descriptions, and only updates companies that exist in table2?

Brian Guan
  • 193
  • 2
  • 12

1 Answers1

1

Use join:

update table1 t1 join
       table2 t2
       on t1.company_id = t2.company_id
    set t1.description = t2.description;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786