advancedupdating MySQL MariaDB SQL Server PostgreSQL SQLite
Update Rows Using Values From Another Table
Use a join inside an `UPDATE` statement to copy or derive values from a related table.
Created Last updated 5/5 supported engines validation-green1 example2 scenarios
Docker-validated Not currently validation-green
Example 1
Copy department names from a lookup table into the employees table
All three employees have their dept_name filled from the matching row in departments. Ada and Carol both map to Engineering (dept_id 1); Bob maps to Finance (dept_id 2). The NULL values are replaced in a single statement.
UPDATE employees
SET
dept_name = (
SELECT
name
FROM
departments
WHERE
departments.id = employees.dept_id
);
SELECT
id,
name,
dept_name
FROM
employees
ORDERBY
id;
Expected result
id
name
dept_name
1
Ada
Engineering
2
Bob
Finance
3
Carol
Engineering
MySQL and MariaDB use UPDATE … JOIN … SET. PostgreSQL and SQL Server use UPDATE … SET … FROM. The resulting data is identical.
Useful when
Where this command helps.
denormalizing a lookup value into a row for reporting or caching
copying a value from a parent table into child rows after a schema change
Explanation
What the command is doing.
Updating rows based on data in another table requires different syntax per engine. MySQL and MariaDB extend UPDATE with a JOIN clause directly. PostgreSQL and SQL Server use a FROM clause to reference the second table. The effect is the same: rows in the target table are updated using matched values from the source.