How to Specifies which columns and values that should be updated in a table in SQL ?
To specify which columns and values should be updated in a table in SQL, you can use the UPDATE
statement with the SET
clause. There are multiple methods to do it:
Method 1: Update a single column
UPDATE table_name
SET column_name = new_value
WHERE condition;
Example:
UPDATE customers
SET city = 'New York'
WHERE customer_id = 1;
This will update the city
column of the customers
table to New York
where the customer_id
is 1.
Method 2: Update multiple columns
UPDATE table_name
SET column1 = new_value1, column2 = new_value2, ...
WHERE condition;
Example:
UPDATE customers
SET city = 'New York', country = 'USA'
WHERE customer_id = 1;
This will update the city
and country
columns of the customers
table to New York
and USA
respectively where the customer_id
is 1.
Method 3: Update with subquery
UPDATE table_name
SET column_name = (SELECT expression FROM table_name WHERE condition)
WHERE condition;
Example:
UPDATE orders
SET total_amount = (SELECT SUM(price*quantity) FROM order_items WHERE order_id = orders.order_id)
WHERE order_id = 1;
This will update the total_amount
column of the orders
table with the sum of price*quantity
from the order_items
table where the order_id
is 1.
Note: It is important to include the WHERE
clause in the UPDATE
statement to avoid updating all the rows in the table.