Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

sql
sql server
community creator
join

How to update data using JOIN

Behzad Ahmad

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 tableName  
JOIN tableName 
ON tableName.colName = tableName.colName  
SET 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 Employee
        INNER JOIN
    Manager ON Employee.Age = Manager.Age 
SET 
    Employee.Name = Manager.Name,
    Employee.City = Manager.City
WHERE Employee.Age IN (21, 25);

SELECT * FROM Employee;

Explanation

  • Line 1: We update the Employee table.

  • 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 Employee to be the same as the name and city of Manager.

  • Line 7: Rows are updated only if the age equals 21 or 25.

  • Line 9: We display the data of the Employee table to the console.

RELATED TAGS

sql
sql server
community creator
join
RELATED COURSES

View all Courses

Keep Exploring