Table of Contents
ToggleThe SQL UPDATE statement is used to modify existing records in a table. You can update one or more columns with new values, based on certain conditions.
The general syntax for the UPDATE statement is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Always include a WHERE clause to specify the records to be updated. If the WHERE clause is omitted, all records in the table will be updated.
Here is a sample of the Customers table:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person and city:
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;
After executing this SQL statement, the customer table will look like this:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 1 | Alfreds Futterkiste | Alfred Schmidt | Obere Str. 57 | Frankfurt | 12209 | Germany |
The following SQL statement will update the ContactName to “Juan” for all customers where the country is “Mexico”:
UPDATE Customers
SET ContactName = 'Juan'
WHERE Country = 'Mexico';
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated:
UPDATE Customers
SET ContactName = 'Juan';
This would update all customers to have “Juan” as the contact name!
