UPDATE Statement
The UPDATE statement is used to modify existing records in a table. You can update a single record or multiple records based on a specified condition.
Syntax
The basic syntax for the UPDATE statement is as follows:
UPDATE table_name
SET column1 = value1,
column2 = value2,
...
WHERE condition;
Parameters:
table_name: The name of the table you want to update.SET column1 = value1, column2 = value2, ...: Specifies the columns to update and their new values.WHERE condition: An optional clause that specifies which records to update. If theWHEREclause is omitted, all records in the table will be updated.
Examples
Example 1: Updating a Single Record
Suppose we have a table named Employees with columns EmployeeID, FirstName, LastName, and Salary. To increase the salary of the employee with EmployeeID = 101:
UPDATE Employees
SET Salary = 65000
WHERE EmployeeID = 101;
Example 2: Updating Multiple Records
To give a 10% raise to all employees in the 'Sales' department:
UPDATE Employees
SET Salary = Salary * 1.10
WHERE Department = 'Sales';
Example 3: Updating Multiple Columns
To update both the department and the salary for a specific employee:
UPDATE Employees
SET Department = 'Marketing',
Salary = 72000
WHERE EmployeeID = 105;
Important Considerations
- Use
WHEREclause cautiously: Always ensure yourWHEREclause is correctly specified to avoid unintended updates to the wrong records. It's a good practice to test yourUPDATEstatement with aSELECTstatement first to see which rows will be affected. - Data types: Ensure that the values you provide for the columns match their respective data types.
- Constraints: Updates must adhere to any constraints defined on the table, such as primary keys, foreign keys, unique constraints, and check constraints.
- Transactions: For critical operations, consider wrapping your
UPDATEstatements within a transaction to allow for rollback if something goes wrong.
Common Clauses with UPDATE
While WHERE is the most common, other clauses can be used:
FROMclause (for more complex updates involving joins):UPDATE e SET e.Salary = e.Salary * 1.05 FROM Employees e JOIN Departments d ON e.DepartmentID = d.DepartmentID WHERE d.DepartmentName = 'IT';