The UPDATE statement is used to modify the existing records in a table.
Warning: Be careful when updating records in a table! Notice the
WHEREclause in theUPDATEstatement. TheWHEREclause specifies which record(s) that should be updated. If you omit theWHEREclause, all records in the table will be updated!
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
Below is a selection from the Customers table:
Customers Table:
| CustomerID | CustomerName | ContactName | Country |
|---|---|---|---|
| 1 | Alfreds Futterkiste | Maria Anders | Germany |
| 2 | Ana Trujillo Emparedados | Ana Trujillo | Mexico |
| 3 | Antonio Moreno Taquería | Antonio Moreno | Mexico |
The following SQL statement updates the first customer (CustomerID = 1) with a new contact name.
UPDATE Customers SET ContactName = 'Alfred Schmidt' WHERE CustomerID = 1;
After the update, the table would look like this:
| CustomerID | CustomerName | ContactName | Country |
|---|---|---|---|
| 1 | Alfreds Futterkiste | Alfred Schmidt | Germany |
| 2 | Ana Trujillo Emparedados | Ana Trujillo | Mexico |
| 3 | Antonio Moreno Taquería | Antonio Moreno | Mexico |
The WHERE clause determines how many records will be updated.
The following SQL statement will update the Country to "United States" for all records where the Country is currently "Mexico".
UPDATE Customers SET Country = 'United States' WHERE Country = 'Mexico';
If you omit the WHERE clause, all records will be updated.
-- This will set the Country to "USA" for ALL customers
UPDATE Customers
SET Country = 'USA';