Update In SQL

In SQL, The "UPDATE" statement is used to modify existing records in a table.

UPDATE Statement allows us to change the values of one or more columns in one or more rows from the table in the database based on specified conditions.

Syntax of UPDATE Statement:

UPDATE tableName
SET columnName1 = value1, columnName2 = value2
WHERE condition;
  • tableName: The name of the table you want to update.

  • SET: Specify the columns you want to update along with their new values.

  • WHERE: Optional, specifies the condition that must be satisfied for the update to occur. If you omit the WHERE clause, all records in the table will be updated.

Update Single Record In SQL Table:

In the below example, we have applied conditions for ex:- "product_code = `A101`" to filter from the table and update it's `product_price` to `2000`.

Example:

UPDATE products
SET product_price = 2000
WHERE product_code = "A101";

Above UPDATE Command will make a change to the unique record in the table whose `product_code` column value is equal to "A101" in the table.

Update Selective Records in Table:

In the below example, update the product_price to `2000` of all products of the Electronic category.

Example:

UPDATE products
SET product_price = 2000
WHERE category = 'Electronic';

Above UPDATE Command will make changes to selective types of records in a single operation.

Update multiple columns, we can specify them in the SET clause:

In this example, updates the `grade` and `status` columns for students who scored `90 or above`.

Example:

UPDATE students
SET grade = 'A', status = 'Pass'
WHERE score >= 90;

Above UPDATE Command will make changes to multiple records in a single operation.

Update all records in table using SET clause:

If we opt-out `WHERE` Clause from the `UPDATE` Statement from the query, then it will update all records in the table.

Example:

UPDATE products
SET product_quantity = 100;

The above command will update all records in the table with `product_quantity` set to `100`.

Note:

Be cautious while using the `UPDATE` statement, especially without opting out of the `WHERE` clause, as it can modify a large number of records unintentionally.