This blog post extends strates how to update more than one column in a table with values from columns in another table and explains how to do it in the three RDBMS that we support.
Table structures and values:
Tablea has four columns: A, B, C, D (A is the primary key column)
Tableb has five columns: A1, B1, C1, D1, E1 (A1 and B1 together constitute the primary key for this table)
The foreign key relationship between the two tables is based on a. A = B. A1
The data in these 2 tables is as follows:
I. tablea
A B c d
1 x Y Z
2 A B C
3 Tb x Z
Ii. tableb
A1 B1 C1 D1 E1
1x1 Y1 Z1 40
2 A1 B1 C1 50
The requirement is to write a SQL to update columns B, C and D in tablea from the columns B1, c1 and D1 from tableb where-ever the join condition satisfies and E1> 40 in tableb.
ORACLE:
Update tablea
Set (B, c, d) = (select B1, C1, D1 from tableb where tableb. A1 = tablea. A and tableb. E1> 40)
Where exists (select 1 from tableb where tableb. A1 = tablea. A and tableb. E1> 40)
/
Results After the update:
A B c d
------------
1 x Y Z
2 A1 B1 C1
3 Tb x Z
SQL Server:
Update tablea
Set B = tableb. B1,
C = tableb. C1,
D = tableb. D1
From tablea, tableb
Where tablea. A = tableb. A1
And tableb. E1> 40
Go
Note: This is an extension in SQL Server I. e. the from clause-it does make it simple to understand and is a nice feature.
Results After the update:
A B c d
------------
1 x Y Z
2 A1 B1 C1
3 Tb x Z
DB2 luw:
-Same as Oracle-
Update tablea
Set (B, c, d) = (select B1, C1, D1 from tableb where tableb. A1 = tablea. A and tableb. E1> 40)
Where exists (select 1 from tableb where tableb. A1 = tablea. A and tableb. E1> 40 );
Results After the update:
A B c d
------------
1 x Y Z
2 A1 B1 C1
3 Tb x Z
Note:
It is very important to make sure that your WHERE clause for the update statement is correct since that is what identifies the records that the update statement is going to qualify and do the update. if it is incorrect, then you can get wrong results. the reason I am mentioning this is because I have seen people write wrong where clauses and then wondering what went wrong because they specified the correct condition in the set clause.
In the above example, if the where condition was omitted, the other record's columns wocould be updated to null value and this will be the final result set:
A B c d
------------
1 null
2 A1 B1 C1
3 Null null