SQL update query using joins
How can you use an SQL UPDATE query with JOIN statements?
This question explores how to update records in one table based on related data from another table using different types of joins in SQL, such as INNER JOIN or LEFT JOIN.
When you need to update data in one table based on information from another, SQL joins come in handy. You can combine tables using a JOIN inside an UPDATE query to update values in a more dynamic and relational way.
Basic Syntax (for most SQL databases like MySQL):
UPDATE table1
JOIN table2 ON table1.id = table2.id
SET table1.column_to_update = table2.source_column
WHERE table2.condition_column = 'some_value';
What does this do?
- JOIN links the two tables based on a related key.
- SET specifies the column(s) to update in the target table.
- WHERE is optional but helps limit which rows are affected.
Example:
Let's say you want to update employee salaries in employees using new values from a salary_updates table:
UPDATE employees e
JOIN salary_updates s ON e.emp_id = s.emp_id
SET e.salary = s.new_salary
WHERE s.effective_from <= CURDATE();
This updates only those employees whose new salary is effective today or earlier.
Important Notes:
- The exact syntax can vary by SQL dialect (e.g., PostgreSQL uses FROM instead of JOIN in updates).
- Always make a backup or use a SELECT first to test your JOIN logic before running an update.
So yes, using joins in UPDATE queries is a powerful way to manage relational data—but always test carefully to avoid unintended changes!