Update-Queries
*What is an Update Query?

The 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.

Syntax :
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;


  • 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!
*Basic Update Query 
Update CountryMaster_bkp06072025 Set CountryName ='India' where CountryId=1

Above query will update Country name which CountryId is 1

*Update multiple columns at once

You can update more than one column in a single query. Just separate each column and value with a comma.
Update CountryMaster_bkp06072025 Set CountryName ='India',CreatedDate=getdate() where CountryId=1

*Updating without a where clause

Be careful! If you forget the 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.

Update CountryMaster_bkp06072025 Set CountryName ='India',CreatedDate=getdate()

*Updating with join

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.

UPDATE employees
SET department_name = 'HR'
FROM employees AS e
JOIN departments AS d ON e.department_id = d.department_id
WHERE d.department_name = 'Human Resources';


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:

BEGIN TRANSACTION;

UPDATE students
SET grade = 'A'
WHERE id = 1;

-- If everything is good, commit the changes
COMMIT;

-- If something goes wrong, you can roll back
-- ROLLBACK;


This ensures that if anything goes wrong in your update process, you can roll back all changes and keep your data safe.