SQL UPDATE

Here is a clear and practical guide to the SQL UPDATE statement`, with best-practice examples you can use immediately.


✅ Basic Syntax (ANSI SQL)

UPDATE table_name
SET column1 = value1,
column2 = value2
WHERE condition;

⚠ Always include a WHERE clause unless you intend to update every row.


✅ Example: Update a Single Row

UPDATE users
SET email = 'new_email@example.com'
WHERE id = 10;

✅ Update Multiple Columns

UPDATE employees
SET salary = salary * 1.10,
department = 'Finance'
WHERE employee_id = 42;

✅ Update All Rows (use with caution!)

UPDATE products
SET is_active = 1;

🔥 Conditional Logic in Updates

Using CASE

UPDATE orders
SET status =
CASE
WHEN shipped_date IS NOT NULL THEN 'Shipped'
ELSE 'Pending'
END;

🔧 Engine-Specific Enhancements

PostgreSQL — UPDATE ... FROM

Allows joins in updates:

UPDATE orders o
SET customer_name = c.name
FROM customers c
WHERE o.customer_id = c.id;

MySQL — Join Update

UPDATE orders o
JOIN customers c ON o.customer_id = c.id
SET o.customer_name = c.name;

🔐 Best Practices for Safe Updates

✔ Always test with a SELECT first using the same WHERE clause
✔ Wrap updates in a transaction if supported
✔ Index columns used in WHERE for performance
✔ Avoid updating huge tables in one transaction — batch if needed

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *