The UPDATE
statement is used to modify existing records in a table.
Syntax
The syntax of the UPDATE
statement is as follows:
UPDATE table_name [AS alias] SET column1 = value1, column2 = value2,... [WHERE condition];
Parameters:
table_name
: The name of the table where you want to update records.alias
: An optional alias you can create fortable_name
.column1, column2, ...
: The names of the columns you want to update.value1, value2, ...
: The new values that you want to insert into the specified columns.condition
: An optional clause that specifies which rows you want to update. If you omit the WHERE clause, all rows in the table will be updated.
Default values
The UPDATE
statement also supports the use of the keyword DEFAULT
to set a column’s value back to its default value. For example:
UPDATE table_name
SET column1 = DEFAULT;
In this case, column1
will be updated with its default value.
Updating multiple columns
The UPDATE
statement can update multiple columns at once:
UPDATE table_name
SET column1 = value1,
column2 = value2,
...;
WHERE clause
The WHERE
clause can be used to specify the rows that you want to update. For example:
UPDATE employees
SET salary = 50000
WHERE id = 1;
In this example, the salary
column of the employee with an id
of 1 is set to 50000.
You can use more complex conditions by combining the WHERE
clause with logical operators such as AND
and OR
:
UPDATE employees
SET salary = 60000
WHERE id = 1 OR id = 2;
In this case, the salary
column of the employees with an id
of 1 or 2 is set to 60000.
Examples
Update a single column:
UPDATE employees
SET salary = 50000
WHERE id = 1;
Update multiple columns:
UPDATE employees
SET first_name = 'John',
last_name = 'Doe'
WHERE id = 1;
Update all rows:
UPDATE employees
SET active = true;
In this case, the active
column for all employees is set to true
.