MySQL UPDATE query
The UPDATE
query in MySQL is used to modify existing records in a table. It allows you to change the values of one or more columns for one or more rows, based on certain conditions. The UPDATE
command is essential for maintaining and managing the data in your database. Here’s a detailed explanation of the UPDATE
query:
1. Basic Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
table_name
: The name of the table you want to update.column1 = value1, column2 = value2, ...
: The columns you want to update and the new values you want to set.WHERE condition
: The condition to specify which rows should be updated. This is crucial; without it, all rows in the table will be updated.
2. Updating a Single Column
You can update a single column for specific rows using the WHERE
clause:
UPDATE employees
SET salary = 60000
WHERE employee_id = 3;
This query updates the salary
of the employee with employee_id = 3
to 60,000.
3. Updating Multiple Columns
You can update multiple columns at once:
UPDATE employees
SET salary = 70000, department = 'HR'
WHERE employee_id = 5;
This query sets the salary
to 70,000 and changes the department
to 'HR' for the employee with employee_id = 5
.
4. Updating All Rows
If you omit the WHERE
clause, the UPDATE
statement will modify all rows in the table:
UPDATE employees
SET department = 'Operations';
This query sets the department
column to 'Operations' for all employees in the table.