Tip of the Day : SQL Update from Joined Table
Updating a table with values from a Joined table.
I run into this question from the guys at work quite a bit, but it’s actually a pretty easy concept once you get the hang of it. If you have two tables that you want to sync values on, and you have a primary/foreign key you can join on, you’re all set.
Update Table1 Set Table1.ThisNeedsUpdated = Table2.WithThisNewValue From Table1 Inner Join Table2 on Table1.ID = Table2.ID
If you get stuck, just remember a few things.
- The table in your “Update” caluse should be the same table in your “From” clause.
- You can join additional tables, nested selects or common table expressions as well and update your main table with values from those as well.
- If you’re working with two tables that have similiar field names, it’s best to fully qualify those fields in your statement to make it more readable.
Please comment if you have any questions or can’t get this working. I’d be glad to help.
Great tip, thanks
Mange
June 18, 2008 at 1:49 pm
Thanks a LOT for this post.
Very VERY usefull!!
Roger
June 25, 2009 at 8:13 pm