MySQL : UPDATE Statement

The UPDATE statement in MySQL is used to modify existing records in a table. It allows you to change the values of one or more columns in a specific row or multiple rows of a table based on specified conditions. Here's the basic syntax of the UPDATE statement:


UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

 

  • table_name: The name of the table from which you want to update records.
  • SET: Specifies the columns that you want to modify along with their new values.
  • column1 = value1, column2 = value2, ...: Assigns new values to the specified columns.
  • WHERE: Optional clause that specifies the conditions that must be met for the update to occur. If omitted, all rows in the table will be updated.

Here's an example to illustrate how to use the UPDATE statement:

Let's say we have a table named `employees` with columns `employee_id`, `first_name`, `last_name`, and `salary`. We want to update the salary of an employee with `employee_id` 101 to $60000.


UPDATE employees
SET salary = 60000
WHERE employee_id = 101;

 

This statement will change the salary of the employee with `employee_id` 101 to $60000.

You can also update multiple columns simultaneously:


UPDATE employees
SET salary = 60000, department = 'Sales'
WHERE employee_id = 101;

 

This will update both the salary and the department of the employee with `employee_id` 101.

And if you want to update multiple rows based on certain conditions, you can use the WHERE clause to specify those conditions:


UPDATE employees
SET salary = salary * 1.1
WHERE department = 'Engineering';

 

This statement will increase the salary of all employees in the 'Engineering' department by 10%.

Always remember to use the WHERE clause carefully to avoid unintended updates to your data.