SQL UPDATE β Modify Existing Records in Tables
Introduction β Why Use SQL UPDATE?
The UPDATE statement in SQL is used to modify existing data in a table. It allows you to change one or more column values for rows that match a specific condition.
Without UPDATE, youβd have to delete and re-insert records β a far less efficient method.
In this guide, youβll learn how to:
- Update a single row or multiple rows
- Use
WHEREto control which records are updated - Update based on calculations or subqueries
- Use
UPDATEwith joins
1. Basic UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
Always include WHERE to avoid changing all rows.
2. Update a Single Record
UPDATE employees
SET salary = 60000
WHERE id = 101;
Modifies the salary for the employee with ID 101.
3. Update Multiple Records
UPDATE products
SET status = 'inactive'
WHERE quantity = 0;
Updates all rows where the condition matches.
4. Update with Expressions
UPDATE employees
SET salary = salary * 1.05
WHERE department = 'Sales';
Increases salary by 5% for all Sales employees.
5. Update Using a Subquery
UPDATE employees
SET department = 'Operations'
WHERE id IN (SELECT employee_id FROM transfers);
Uses data from another table to filter rows.
6. Update with JOIN (varies by SQL dialect)
-- MySQL / PostgreSQL
UPDATE employees
SET employees.salary = new_salaries.salary
FROM new_salaries
WHERE employees.id = new_salaries.id;
Useful for updating based on related table data.
7. Update All Rows (Use Carefully)
UPDATE products
SET discount = 10;
Applies the same change to every row β use only if intended.
Best Practices
| Do This | Avoid This |
|---|---|
Always use a WHERE clause | Updating all rows by mistake |
| Backup before bulk updates | Skipping transactions on large data |
Test your query with SELECT | Assuming UPDATE affects one row |
| Use JOINs and subqueries wisely | Updating without validating results |
Summary β Recap & Next Steps
The UPDATE command is essential for modifying existing records safely and efficiently. From adjusting salaries to bulk status changes, UPDATE gives you precise control.
Key Takeaways:
- Use
UPDATEwithSETto change values - Always add a
WHEREclause to scope the update - Can use expressions, subqueries, and joins
- Use transactions when modifying large datasets
Real-World Relevance:UPDATE is used in inventory management, account maintenance, audit logs, and operational workflows.
Next: Learn how to remove data using SQL DELETE.
FAQ β SQL UPDATE
Can I update multiple columns at once?
Yes. Separate them with commas in the SET clause.
What if I forget the WHERE clause?
All rows in the table will be updated. Always double-check.
Can I use a subquery in an UPDATE?
Yes, subqueries are often used to filter which rows are updated.
Can I undo an UPDATE?
Only if youβve used a TRANSACTION and havenβt committed yet. Otherwise, no.
Can I update data from another table?
Yes, using joins or subqueries depending on your SQL dialect.
Share Now :
