The SQL UPDATE statement is a powerful tool for modifying existing data in a table.
It allows you to change one or more fields in a specific record or multiple records, and it can be used in conjunction with other statements like subqueries.
Syntax
The basic syntax for the SQL UPDATE statement is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE some_column = some_value;
- The UPDATE keyword is used to update existing data in a table.
- The SET keyword is used to specify the columns and values that will be updated.
- The WHERE keyword is used to specify which record or records should be updated.
Example
Consider a table named "employees" with the following fields: id, first_name, last_name, and salary.
To update the salary of an employee with id = 1, the SQL statement would be:
UPDATE employees
SET salary = 50000
WHERE id = 1;
This statement would update the salary of the employee with id = 1 to 50000.
Multiple Columns Update
It's also possible to update multiple columns at once using the SQL UPDATE statement.
The following example updates the first_name and last_name of an employee with id = 1:
UPDATE employees
SET first_name = 'John', last_name = 'Doe'
WHERE id = 1;
This statement would update the first_name to "John" and last_name to "Doe" of the employee with id = 1.
Multiple Records Update
You can also update multiple records at once using the SQL UPDATE statement.
The following example updates the salary of all employees to 50000:
UPDATE employees
SET salary = 50000;
This statement would update the salary of all employees to 50000.
Updating with a Subquery
You can also use a subquery in the SET clause of an UPDATE statement.
The following example increases the salary of all employees by 10% whose department is IT:
UPDATE employees
SET salary = salary * 1.1
WHERE department = (SELECT id FROM departments WHERE name = 'IT');
This statement would increase the salary of all employees by 10% whose department is IT by using a subquery.