Overview
The UPDATE
statement modifies existing rows in a table. It allows you to change column values based on a specified condition.
Syntax
UPDATE [TOP (expression)] [schema_name.]table_name SET column1 = expression1, column2 = expression2, ... [WHERE search_condition] [;]
Components
- TOP (expression): Optional limit on rows to update (SQL Server).
- schema_name: Optional schema qualifier.
- table_name: The target table.
- SET: Defines column assignments.
- WHERE: Filters rows to be updated. Omit to affect all rows.
Examples
1. Simple Update
UPDATE Employees SET Salary = Salary * 1.10 WHERE Department = 'Sales';
2. Updating Multiple Columns
UPDATE Products SET Price = Price - 5, Stock = Stock + 20 WHERE Category = 'Electronics';
3. Using a Subquery
UPDATE Orders o SET o.Status = 'Shipped' FROM (SELECT OrderID FROM Orders WHERE ShippedDate IS NOT NULL) s WHERE o.OrderID = s.OrderID;
Try It Live
Best Practices
- Always use a
WHERE
clause unless you intend to update every row. - Back up data or run the query within a transaction.
- Test the
WHERE
condition with aSELECT
first. - Consider indexing columns used in the
WHERE
clause.