Updating Data in SQL

This tutorial will guide you through the process of modifying existing data within your SQL database using the UPDATE statement.

The UPDATE Statement

The UPDATE statement is used to change records in a table. It's a fundamental operation for managing your database's content.

Basic Syntax

The general syntax for the UPDATE statement is as follows:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Important Note: Always specify a WHERE clause when updating data. If you omit it, you will update all records in the table, which is rarely desired.

Updating Specific Rows

To update only certain rows, you use the WHERE clause. This clause filters the records that will be affected by the UPDATE statement.

Example: Updating a Single Record

Let's say we have a table named Customers with columns CustomerID, FirstName, LastName, and Email. We want to change the email address for the customer with CustomerID 101.

UPDATE Customers
SET Email = 'jane.doe.new@example.com'
WHERE CustomerID = 101;

This statement will find the row where CustomerID is 101 and update its Email column to 'jane.doe.new@example.com'.

Updating Multiple Columns

You can update multiple columns in a single UPDATE statement by separating the column assignments with commas.

Example: Updating Multiple Fields

Suppose we want to update both the FirstName and LastName for the customer with CustomerID 102.

UPDATE Customers
SET FirstName = 'John', LastName = 'Smith'
WHERE CustomerID = 102;

Updating with Conditions

The WHERE clause can include complex conditions using logical operators like AND, OR, and NOT, as well as comparison operators (=, !=, <, >, <=, >=) and other operators like LIKE, IN, and BETWEEN.

Example: Updating Based on Multiple Criteria

Update the Email for all customers in 'New York' whose CustomerID is greater than 50.

UPDATE Customers
SET Email = 'generic.update@example.com'
WHERE City = 'New York' AND CustomerID > 50;

Updating with Values from Other Tables (Joins)

While not standard SQL for all database systems, many RDBMS (like SQL Server, MySQL, PostgreSQL) support updating a table based on values from another table using joins. The syntax can vary.

Example (SQL Server Syntax): Updating from another table

Imagine updating the Price in Products based on the NewPrice in a temporary table PriceUpdates for matching ProductID.

UPDATE P
SET P.Price = PU.NewPrice
FROM Products AS P
INNER JOIN PriceUpdates AS PU ON P.ProductID = PU.ProductID;

Summary

The UPDATE statement is a powerful tool for data manipulation. Remember to: