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.
UPDATE StatementThe 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.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Let's break down the components:
UPDATE table_name: Specifies the table you want to modify.SET column1 = value1, column2 = value2, ...: Identifies the columns to update and the new values they should receive. You can update multiple columns in a single statement.WHERE condition: This clause is critical. It specifies which rows should be updated. If you omit the WHERE clause, all rows in the table will be updated, which is rarely the desired outcome.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.
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;
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.
WHERE clause.WHERE Clause: Before running an UPDATE statement, it's a good practice to run a SELECT statement with the same WHERE clause to verify which rows will be affected. For example: SELECT * FROM Employees WHERE Department = 'Sales';UPDATE statements within transactions. This allows you to undo the changes if something goes wrong using ROLLBACK.NULL ValuesYou can set a column to NULL using the SET column_name = NULL syntax within the UPDATE statement.
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).
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;