UPDATE
query allows you to change data that’s already stored in a table. You specify the column(s) you want to update and the new value you want to set.- table_name: The table where you want to update the data.
- SET: Specifies which columns you want to change and the new values.
- WHERE: Filters the rows that should be updated. Always use WHERE to avoid updating all rows in the table by mistake!
WHERE
clause, the update will affect every single row in the table. It's best practice to always use WHERE
unless you really want to update all records.In SQL Server, you can also use a JOIN
to update records in one table based on data from another table. This is handy when you need to update a table using data from a related table.
Example:
Suppose you have an employees
table and a departments
table, and you want to update the department name for a specific employee.
This will update the department_name
of employees whose department matches Human Resources.
*Rolling Back Updates Using Transactions (Optional)
If you're making several updates and want to make sure everything is correct before committing, you can use transactions. This way, if something goes wrong, you can roll back the changes.
Example:
This ensures that if anything goes wrong in your update process, you can roll back all changes and keep your data safe.