
For an instructor lead, in-depth look at learning SQL click below.
The UPDATE statement is one of the most commonly used commands in SQL (Structured Query Language). Its main function is to modify the existing records in a table. It’s an essential tool for any SQL programmer, as data rarely stays the same and needs to be updated regularly to reflect the most current information.
UPDATE Syntax
The UPDATE statement is generally written as follows:
1 2 3 4 5 |
UPDATE table_name SET column1 = value1, column2 = value2,... WHERE some_column=some_value; |
The UPDATE statement has three main components – the table name, the SET clause, and the WHERE clause:
- The table_name is the name of the table where you want to update the data.
- The SET clause is used to specify the column names and the new values you want to assign to them.
- The WHERE clause is used to determine which rows should be updated. If you leave out the WHERE clause, all rows in the table will be updated!
Examples of UPDATE Statement
Suppose we have a Customers table, and we want to update the contact number of a customer with a specific CustomerID:
1. Customers Table
1 2 3 |
SELECT * FROM Customers; |
Say we get the following data:
|CustomerID|CustomerName|ContactNumber|
|—|—|—|
|1|John|123456789|
|2|Smith|234567891|
|3|Michael|345678912|
2. UPDATE Statement Example
If customer John changed his contact number and we need to update it, we use the UPDATE statement as follows:
1 2 3 |
UPDATE Customers SET ContactNumber = '987654321' WHERE CustomerID = 1; |
Let’s break this down:
- The table we want to update is Customers.
- We then use the SET clause to change the value of ContactNumber to ‘987654321’.
- Finally, we use the WHERE clause to specify that we only want to update the row where CustomerID is 1.
Conclusion
The UPDATE statement in SQL is a powerful command that allows you to efficiently change data in your tables. Understanding how to use this statement effectively can greatly enhance your SQL skills and make data management tasks much easier.