π SQL UPDATE Statement β How to Modify Data in SQL Tables
Need to correct or change existing data in your SQL database? The
UPDATEstatement is your go-to command for modifying values without deleting or recreating rows.
This tutorial walks you through the SQL UPDATE syntax, usage patterns, best practices, and real-world examples to help you confidently update your data.
π What is the SQL UPDATE Statement?
The UPDATE command in SQL is used to modify existing records in a table. You can update a single column, multiple columns, one row, or several rows at once based on a condition.
π§Ύ SQL UPDATE Syntax
UPDATE table_name
SET column1 = value1,
column2 = value2,
...
WHERE condition;
β οΈ Always use the
WHEREclause unless you want to update all rows in the table!
β Example: Update a Single Row
UPDATE employees
SET salary = 85000
WHERE emp_id = 101;
This updates the salary of the employee with ID 101.
β Example: Update Multiple Columns
UPDATE employees
SET emp_name = 'Neha Singh',
department = 'Finance'
WHERE emp_id = 102;
β οΈ Update All Rows (Use With Caution!)
UPDATE employees
SET bonus = 5000;
This adds a bonus to every employee in the table. Useful in some cases, but risky if done by mistake!
π§ Use Conditional Expressions in UPDATE
You can use conditional logic like CASE:
UPDATE employees
SET bonus = CASE
WHEN department = 'Sales' THEN 10000
WHEN department = 'HR' THEN 5000
ELSE 3000
END;
π Update Using a Subquery
UPDATE employees
SET salary = (
SELECT AVG(salary)
FROM employees
WHERE department = 'IT'
)
WHERE department = 'Marketing';
π Best Practices for SQL UPDATE
- β
Always test your query with a
SELECTstatement first to preview affected rows. - β
Use transactions (
BEGIN,ROLLBACK,COMMIT) if making bulk updates. - π¨ Never run an
UPDATEwithout aWHEREclause unless itβs intentional. - π‘οΈ Backup critical data before large updates.
- π§ͺ Use staging/test environments before production updates.
π― Real-Life Use Cases
| Use Case | Example SQL |
|---|---|
| Update salary after annual review | SET salary = salary * 1.10 |
| Change department for an employee | SET department = 'R&D' WHERE emp_id = 105 |
| Reset login attempts after password change | SET login_attempts = 0 |
| Update prices in an e-commerce catalog | SET price = price * 1.05 |
π Summary
UPDATEchanges one or more values in an existing row.- It supports conditional updates, multi-column updates, and subqueries.
- Always use
WHEREto target specific rows. - One of the most powerful tools in your SQL toolkit for data maintenance.
π Recommended Next Reads
- π§± SQL INSERT β Learn how to add new records
- π§Ή SQL DELETE β Remove specific rows safely
- π SQL SELECT β Query the data you’re updating
- π SQL WHERE Clause β Master conditional filtering