How do I UPDATE from a SELECT in SQL Server?
How do I UPDATE from a SELECT in SQL Server?
Student
Skilled in SEO, content writing, and digital marketing. Completed several years of working in many organizations including multinational companies. I love to learn new things in life that keep me motivated.
To update from a select in SQL Server, you can use the
UPDATEstatement with theFROMclause. TheUPDATEstatement allows you to update rows in a table, and theFROMclause allows you to select rows from another table.The syntax for updating from a select in SQL Server is as follows:
SQL
The
table_nameis the name of the table that you want to update. Thecolumn1,column2, etc. are the columns that you want to update. Thevalue1,value2, etc. are the new values for the columns. Thetable1is the name of the table that you want to select from. Theconditionis an optional clause that specifies the rows that you want to update.For example, the following code will update the
CustomerNamecolumn in theCustomerstable toJohn Smithfor all customers where theCustomerIDis 100:SQL
This code will first select the row from the
Customerstable where theCustomerIDis 100. Then, it will update theCustomerNamecolumn in theCustomerstable toJohn Smithfor the selected row.You can also use the
FROMclause in theUPDATEstatement to select rows from another table and update the rows in the current table based on the selected rows. For example, the following code will update theCustomerNamecolumn in theCustomerstable to the value of theCustomerNamecolumn in theOrderstable for all customers who have placed an order:SQL
This code will first join the
CustomersandOrderstables on theCustomerIDcolumn. Then, it will update theCustomerNamecolumn in theCustomerstable to the value of theCustomerNamecolumn in theOrderstable for all rows where theCustomerIDis the same in both tables.