Summary: updating data is one of the most important tasks when you work with databases. In this tutorial, you will learn how to use MySQL UPDATE statement to update data in database tables. Introduction to MySQL UPDATE statement
The
The following illustrates the MySQL
UPDATE [LOW_ PRIORITY] [IGNORE] table_name [, table_name...]
SET column_name1 = expr1
[, column_name2=expr2 ...]
[WHERE condition]
Let’s examine the
MySQL UPDATE examplesLet’s practice with a couple of examples in the MySQL sample database. MySQL UPDATE a single column in a table
In this example, we are going to update the email of First, to make sure that we update the email successfully, we query Mary’s email using the SELECT statement as follows:
SELECT firstname,
lastname,
email
FROM employees
WHERE employeeNumber = 1056
Second, we can update her current email to the new email
UPDATE employees
SET email = 'mary.patterso@classicmodelcars.com'
WHERE employeeNumber = 1056
Because we just want to update Mary’s record so we use the
Third, we execute the
SELECT firstname,
lastname,
email
FROM employees
WHERE employeeNumber = 1056
MySQL UPDATE multiple columns
To update multiple columns, you need to specify them in the
UPDATE employees
SET lastname = 'Hill',
email = 'mary.hill@classicmodelcars.com'
WHERE employeeNumber = 1056;
Le’ts check the changes:
SELECT firstname,
lastname,
email
FROM employees
WHERE employeeNumber = 1056;
MySQL UPDATE from SELECT statement
You can provide the values for the
SELECT customername,
salesRepEmployeeNumber
FROM customers
WHERE salesRepEmployeeNumber IS NULL;
We can take any sale representative and update for those customers:
UPDATE customers
SET salesRepEmployeeNumber =
(
SELECT employeeNumber
FROM employees
WHERE jobtitle = 'Sales Rep'
LIMIT 1
)
WHERE salesRepEmployeeNumber IS NULL;
The In this tutorial, you’ve learned how to use MySQL UPDATE statement to update data in database tables. (责任编辑:IT) |