SQL UPDATE Statement
The UPDATE statement is used to modify existing records in a table. It allows you to change the values of one or more columns in rows that meet specific criteria.
Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Parameters
table_name: The name of the table you want to update.column1, column2, ...: The names of the columns you want to update.value1, value2, ...: The new values to assign to the specified columns. These can be literal values, expressions, or even values from other columns.WHERE condition: (Optional) A condition that specifies which rows to update. If theWHEREclause is omitted, all rows in the table will be updated.
Examples
Example 1: Update a single column for a specific record
This example updates the Email of a customer with CustomerID 10.
UPDATE Customers
SET Email = 'new.email@example.com'
WHERE CustomerID = 10;
Example 2: Update multiple columns for multiple records
This example increases the DiscountPercentage by 5% for all customers in 'USA' and updates their ModifiedDate.
UPDATE Customers
SET DiscountPercentage = DiscountPercentage + 0.05,
ModifiedDate = GETDATE()
WHERE Country = 'USA';
Example 3: Update a column based on another table (using a subquery)
This example updates the StockQuantity in the Products table based on the total quantity ordered in the OrderDetails table.
UPDATE Products
SET StockQuantity = StockQuantity - (
SELECT SUM(Quantity)
FROM OrderDetails
WHERE OrderDetails.ProductID = Products.ProductID
)
WHERE EXISTS (
SELECT 1
FROM OrderDetails
WHERE OrderDetails.ProductID = Products.ProductID
);
Important Considerations
- Always use a
WHEREclause unless you explicitly intend to update every row in the table. Omitting theWHEREclause can lead to unintended data loss or modification. - Backup your data before performing any significant
UPDATEoperations. - Test your
UPDATEstatements on a development or staging environment before running them on production. - Understand the data types of the columns you are updating to ensure compatibility with the new values.
Related Topics
SQL SELECT StatementSQL INSERT Statement
SQL DELETE Statement
SQL Data Types