How to merge / update 2 identical SQL tables

I have two SQL tables with the same structure. One of them is an updated version of the second. How can I combine 2 so that new table entries take precedence over others, and records that do not have updates in the new table are still included?

Source table ID (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

+4
source share
3 answers

coalescewill return the first nonzero value. In combination with left jointhis, it will first use the new data, and if null - the old.

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
+5
source
UPDATE o
SET Name=u.Name
    ,Address=u.Address
from [original] o
inner join [updated] u on u.id = o.id
+2
source

Try the connection:

Select id as uid, name, address from new_table
Union 
Select id, name, address from old_table
Where id not in (select id from new_table)

Also, do not try to use id as the column name. A very bad idea.

0
source

All Articles