Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to merge/update 2 identical SQL tables

Tags:

sql

I have 2 SQL tables with the same structure. One is an updated version of the second. How can I merge the 2 so that the newer table's records take precedence over the other, and records that do not have updates in the newer table are still included?

Original Table ID (is primary key):

ID, NAME, ADDRESS
11   AL    1 main street
22   BOB   2 main street
33   CHAZ  3 main street

Updated Table

ID, NAME, ADDRESS
11  AL     99 maple street
22  BOB    2 main street

Result I want

ID, NAME, ADDRESS
11    AL   99 maple street
22    BOB  2 main street
33    CHAZ 3 main street

thanks, MC

like image 911
user2714083 Avatar asked Mar 16 '23 01:03

user2714083


2 Answers

coalesce will return the first non-null value. Combined with a left join this will first use the new data and if null the old one.

select coalesce(u.id, o.id) as id,
       coalesce(u.name, o.name) as name,
       coalesce(u.address, o.address) as address
from original_table o
left join updated_table u on u.id = o.id
like image 90
juergen d Avatar answered Mar 21 '23 03:03

juergen d


UPDATE o
SET Name=u.Name
    ,Address=u.Address
from [original] o
inner join [updated] u on u.id = o.id
like image 35
UnhandledExcepSean Avatar answered Mar 21 '23 04:03

UnhandledExcepSean