Updating Data in Relational Databases

This tutorial guides you through the process of modifying existing data within relational database tables. Understanding how to update records is crucial for maintaining accurate and up-to-date information.

The UPDATE Statement

The primary SQL command for modifying data is the UPDATE statement. It allows you to change values in one or more columns of a specified row or set of rows in a table.

Syntax

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

Let's break down the components:

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 = 60000
WHERE EmployeeID = 101;

This statement will find the row where EmployeeID is 101 and set its Salary to 60000.

Example 2: Updating Multiple Columns

To update both the LastName and Email for the employee with EmployeeID 102:

UPDATE Employees
SET LastName = 'Smithers', Email = 'j.smithers@example.com'
WHERE EmployeeID = 102;

Example 3: Updating Based on Another Column's Value

Let's say we want to give a 10% raise to all employees in the 'Sales' department. We'll assume there's a Department column.

UPDATE Employees
SET Salary = Salary * 1.10
WHERE Department = 'Sales';

Here, Salary * 1.10 calculates the new salary, and the WHERE clause filters for employees in the 'Sales' department.

Important Considerations

Note on NULL Values

You can set a column to NULL using the SET column_name = NULL syntax within the UPDATE statement.

Advanced Updating Techniques

More complex scenarios might involve updating data based on joins with other tables. The syntax for this can vary slightly between different SQL database systems (like SQL Server, PostgreSQL, MySQL).

Example with a Join (Conceptual - syntax may vary)

Imagine updating OrderTotal in an Orders table based on the sum of items from an OrderDetails table.

-- Example syntax for SQL Server
UPDATE O
SET O.OrderTotal = OD.TotalItemPrice
FROM Orders AS O
INNER JOIN (
    SELECT OrderID, SUM(Price * Quantity) AS TotalItemPrice
    FROM OrderDetails
    GROUP BY OrderID
) AS OD ON O.OrderID = OD.OrderID;