Update command in SQL
The UPDATE statement in SQL is used to modify existing records in a table. We can update one or more columns for one or more rows, and it’s typically used with a WHERE clause to specify which rows should be updated. If the WHERE clause is omitted, all rows in the table will be updated.
SQL Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example: Let's assume we have an employees table with the following structure:
SQL
CREATE TABLE employees ( employee_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR(100), department_id INT, salary DECIMAL(10, 2) );
Example: Update a Single Column Suppose we want to update the email address of the employee with employee_id 1.
SQL
UPDATE employees
SET email = 'new.email@example.com'
WHERE employee_id = 1;
SET email = 'new.email@example.com'
WHERE employee_id = 1;
Explanation:
- UPDATE employees: Specifies the table to update.
- SET email = 'new.email@example.com': Specifies the new value for the email column.
- WHERE employee_id = 1: Specifies the condition that must be met for a row to be updated. In this case, only the row where employee_id is 1 will be updated.
SQL
UPDATE employees
SET employee_id = 10
WHERE employee_id = 1;
SET employee_id = 10
WHERE employee_id = 1;
Explanation:
- UPDATE employees: Specifies the table to update (employees).
- SET employee_id = 10: Specifies the new value for the employee_id column (setting it to 10).
- WHERE employee_id = 1: Specifies the condition that determines which row(s) to update (only rows where employee_id is 1). This statement will change the employee_id of the employee with employee_id 1 to 10.