SQL - Update Query
The UPDATE statement in SQL is used to modify existing records in a table. It allows you to update the values of one or more columns in one or more rows based on specified conditions. The UPDATE statement is commonly used to make changes to existing data in a table, such as updating records with new values or modifying specific fields.
Syntax:
The basic syntax of the UPDATE statement is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example:
Let's assume we have a "Customers" table with the following columns:
CustomerID (unique identifier for each customer)
FirstName (first name of the customer)
LastName (last name of the customer)
Email (email address of the customer)
Phone (phone number of the customer)
To update the email address of a customer in the "Customers" table, we can use the UPDATE statement:
UPDATE Customers
SET Email = '[email protected]'
WHERE CustomerID = 1;
Explanation:
The UPDATE keyword is followed by the name of the table you want to update. In this case, it's the "Customers" table.
The SET keyword is used to specify the columns and their new values. In this example, we update the Email column and set it to '[email protected]'.
The WHERE clause is optional but highly recommended to specify the condition for updating specific rows. In this case, we update the email address of the customer with CustomerID = 1.
By executing this query, the email address of the customer with CustomerID = 1 will be updated to '[email protected]'.
Updating Multiple Columns:
You can update multiple columns in a single UPDATE statement by separating each column and its new value with a comma. For example:
UPDATE Customers
SET FirstName = 'John', LastName = 'Doe'
WHERE CustomerID = 1;
This query updates both the FirstName and LastName columns of the customer with CustomerID = 1.
Updating Multiple Rows:
To update multiple rows, you can specify multiple conditions in the WHERE clause or omit the WHERE clause altogether. For example:
UPDATE Customers
SET Phone = '000-000-0000'
WHERE LastName = 'Smith';
This query updates the Phone column for all customers with the last name 'Smith'.