How do I UPDATE from a SELECT in SQL Server?
How can you update a table in SQL Server using data from another table? What is the correct way to use UPDATE with a SELECT statement? Let’s explore the best methods to achieve this!
If you need to update a table in SQL Server using values from another table, you can do this efficiently using the UPDATE statement with a JOIN or a FROM clause. Here’s how you can do it!
1. Using UPDATE with JOIN (Recommended Approach)
This method is commonly used when updating a table with data from another table:
UPDATE t1
SET t1.column_name = t2.column_name
FROM Table1 t1
JOIN Table2 t2 ON t1.id = t2.id
WHERE t2.some_column = 'some_value';
- Efficient for large datasets
- Allows filtering with WHERE to update specific rows
2. Using UPDATE with a Subquery
If you don’t need a join, you can update using a SELECT subquery:
UPDATE Table1
SET column_name = (SELECT column_name FROM Table2 WHERE Table2.id = Table1.id)
WHERE EXISTS (SELECT 1 FROM Table2 WHERE Table2.id = Table1.id);
- Useful when updating from a single column result
- Make sure the subquery returns only one row per update
3. Using MERGE (For Complex Updates)
If you need to update or insert data based on conditions, use MERGE:
MERGE INTO Table1 AS t1
USING Table2 AS t2
ON t1.id = t2.id
WHEN MATCHED THEN
UPDATE SET t1.column_name = t2.column_name;
- Ideal for conditional updates
- Can also handle inserts (WHEN NOT MATCHED THEN INSERT)
Final Tips:
- ✅ Always backup your data before running an update!
- ✅ Use WHERE conditions to avoid updating unintended rows.
- ✅ Test your query with a SELECT before applying the update.