Skip to content
Advertisement

Adding column in table with the values in another if matched

I have two tables:

table1

A B C
A1 B1 C1
A2 B2 C2
A3 B3 C3
A4 B4 C4
A5 B5 C5
A6 B6 C6

table2

A D
A1 D1
A3 D3
A5 D5
A6 D6

I would like to have table 1 updated with a column D which shows the value in column D joining by A. However, Is altering table 1 adding a column D and then merging both tables and update when matched the way to go or is there any better approach?

Advertisement

Answer

You can just join the value in when you need it:

select t1.*, t2.d
from table1 t1 left join
     table2 t2
     on t1.a = t2.a;

If that is not sufficient, you can add the column:

alter table1 add d <type>;

Then you can update it:

update table1 t1
    set d = (select t2.d from table2 t2 where t2.a = t1.a)
    where exists (select t2.d from table2 t2 where t2.a = t1.a);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement