Description
Update records in a database table, modifying specified field values to new values.
Syntax
Required Parameters
target_table
: The name of the target table where records need to be updated.column_name
: The name of the column that needs to be updated.new_value
: The new value, which can be a constant, variable, function call, arithmetic operator, string operation, etc. Subqueries are supported.
Optional Parameters
-
condition
: The condition for the update operation, used to specify which records need to be updated. The condition can include subqueries and expressions. -
ORDER BY ...
: Update after sorting by the specified columns:- Typically used in conjunction with
LIMIT
to control the order of updates. - Suitable for batch updates or processing data by priority (e.g., processing the most recent records first).
- Typically used in conjunction with
-
LIMIT row_count
: Limit the maximum number of rows to be updated:- Commonly used for batch-updating large tables to avoid table locks or excessively long transactions.
- Should be used with
ORDER BY
to ensure deterministic update order.
Example
Example 1: Update a single field value
Suppose we have a table named employees
that contains the ID, name, and salary of employees. Now we want to increase the salary of the employee with ID 1 by 1000 yuan.
Example 2: Updating Multiple Field Values Simultaneously
Continuing with the employees
table, now we want to increase the salary of the employee with ID 1 by 1000 yuan and change the position from "Developer" to "Senior Developer".
Example 3: Using Subqueries to Update Field Values
Assuming we have a table named orders
that contains order ID, customer ID, and order amount. We also have a table named customers
that contains customer ID, name, and membership level. Now we want to increase the order amount of all VIP customers by 10%.
Precautions
- When performing update operations, please ensure that the
WHERE
clause is correct to avoid mistakenly updating records that should not be updated. - Before performing update operations in the production environment, it is recommended to first verify in the testing environment.