The SQL UPDATE
statement is used to modify existing records in a table. It allows you to change the values of one or more columns in one or more rows based on specified conditions.
Here's the basic syntax of the UPDATE
statement:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Explanation of each part:
UPDATE
: Keyword indicating that you want to update existing records.table_name
: The name of the table from which you want to update records.SET
: Keyword indicating the columns you want to update and the new values you want to assign to them.column1 = value1, column2 = value2, ...
: Specifies the columns you want to update and the new values you want to assign to them.WHERE
: Optional keyword that allows you to specify conditions that must be met for the update to occur. If omitted, all rows in the table will be updated.condition
: Specifies the condition(s) that must be met for the rows to be updated. If omitted, all rows in the table will be updated.Example:
Suppose we have a table called 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 50000:
UPDATE employees
SET salary = 50000
WHERE employee_id = 101;
This statement will change the salary
column to 50000 for the employee whose employee_id
is 101.
You can also update multiple columns at once:
UPDATE employees
SET salary = 50000, department = 'IT'
WHERE employee_id = 101;
This statement updates both the salary
and department
columns for the employee with employee_id
101.
If you omit the WHERE
clause, the UPDATE
statement will modify all rows in the table:
UPDATE employees
SET salary = 50000;
This statement would set the salary
column to 50000 for all employees in the employees
table. Be cautious when using UPDATE
without a WHERE
clause, as it can unintentionally affect a large number of records.