The UPDATE statement in SQL is used to modify existing rows in a table. It can update a single row, multiple rows, or even use data from another table to perform the update. This is a core part of data manipulation, enabling you to change stored data based on conditions or joins.
Basic Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;table_name: The table to be updated.SET: Specifies the columns to be modified and their new values.WHERE: Filters which rows should be updated. OmittingWHEREupdates all rows.
Example 1: Updating a Single Row
Update an employee’s salary by increasing it by 10%:
UPDATE employees
SET salary = salary * 1.10
WHERE employee_id = 123;Explanation:
- Only the row with
employee_idequal to123is updated. - The salary is multiplied by
1.10, reflecting a 10% raise.
Example 2: Updating Multiple Rows
Set the status of all employees in the “Sales” department to ‘active’:
UPDATE employees
SET status = 'active'
WHERE department = 'Sales';Explanation:
- All rows where
departmentis “Sales” will have theirstatuscolumn updated to'active'.
Example 3: Updating Data from Another Table
Method A: Using a Subquery
Update the price of products based on a multiplier from another table:
UPDATE products
SET price = price * (
SELECT multiplier
FROM pricing_factors
WHERE pricing_factors.product_id = products.product_id
)
WHERE EXISTS (
SELECT 1
FROM pricing_factors
WHERE pricing_factors.product_id = products.product_id
);Explanation:
- For each product, the
priceis multiplied by amultiplierretrieved frompricing_factors. - The
WHERE EXISTSclause ensures that only products with a corresponding entry inpricing_factorsare updated.
Method B: Using a JOIN in PostgreSQL
Update an orders table using discount information from a discounts table:
UPDATE orders
SET amount = orders.amount * discounts.discount_multiplier
FROM discounts
WHERE orders.customer_id = discounts.customer_id
AND discounts.valid = true;Explanation:
- This query joins
orderswithdiscountsoncustomer_id. - It updates the
amountby applying thediscount_multiplierfor valid discounts. - The
FROMclause (supported in PostgreSQL) is used to join tables directly in an update.
Related Notes
- SQL Insert – How to add new rows to a table.
- SQL Delete – Removing rows from a table.
- SQL Transactions and Errors – Grouping statements to maintain atomicity.
- SQL select distinct – Retrieving data from tables.