How to update data using JOIN
Overview
SQL UPDATE JOIN is used to update the data of one table by using the data of some other table and some JOIN conditions.
Syntax
UPDATE tableNameJOIN tableNameON tableName.colName = tableName.colNameSET tableName.colName = tableName.colName;
Code example
Let’s look at an example to understand the concept.
Suppose we have a table Employee with the following data:
SELECT * FROM Employee
We have another table named Manager with the following data:
SELECT * FROM Manager
Now we write a query in which we update the values of the Employee table by using the values of Manager table for the rows where Age is equal to 21 or 25. We also want to update the Name and the City.
UPDATE EmployeeINNER JOINManager ON Employee.Age = Manager.AgeSETEmployee.Name = Manager.Name,Employee.City = Manager.CityWHERE Employee.Age IN (21, 25);SELECT * FROM Employee;
Explanation
-
Line 1: We update the
Employeetable. -
Line 3: We join both the tables on the basis of their age.
-
Lines 5 to 6: We set the name and the city of
Employeeto be the same as the name and city ofManager. -
Line 7: Rows are updated only if the age equals 21 or 25.
-
Line 9: We display the data of the
Employeetable to the console.