Laravel

A Comprehensive Guide to Updating Data in SQL Tables with Examples

K

Kolawole

Oct 4, 2023

1 year ago 298 words 2 min read
Whether you need to correct errors, modify records, or implement changes, SQL offers powerful tools for this purpose.

In SQL (Structured Query Language), the ability to update data in tables is crucial for maintaining accurate and up-to-date information in your database. Whether you need to correct errors, modify records, or implement changes, SQL offers powerful tools for this purpose. In this guide, we'll explore how to update data in SQL tables with examples.


Basic Syntax for Updating Data

UPDATE TableName
SET Column1 = NewValue1, Column2 = NewValue2, ...
WHERE Condition;

Breakdown:

  • TableName: The table you want to update.
  • SET: Lists the columns and their new values.
  • Column1 = NewValue1, ...: Defines updates to one or more columns.
  • WHERE: Specifies which rows to update (omit with caution—otherwise all rows will be updated).

Examples

Example 1: Updating a Single Row

UPDATE Customers
SET Email = '[email protected]'
WHERE CustomerID = 101;

Explanation: Updates the Email of the customer with CustomerID = 101.


Example 2: Updating Multiple Rows

UPDATE Customers
SET Email = '[email protected]'
WHERE City = 'New York';

Explanation: Updates the Email field for all customers in New York.


Example 3: Updating Data Based on Calculations

UPDATE Products
SET Price = Price * 1.10;

Explanation: Increases all product prices by 10%. Uses a calculation in the SET clause.


Handling Special Cases

Updating NULL Values

UPDATE Customers
SET PhoneNumber = '555-555-5555'
WHERE PhoneNumber IS NULL;

Explanation: Replaces NULL phone numbers with a default value.


Updating with Subqueries

UPDATE Products
SET Discount = (SELECT AVG(Discount) FROM Products);

Explanation: Sets each product’s Discount to the average discount across all products, using a subquery.


Conclusion

The UPDATE statement is a fundamental SQL tool for modifying data.

  • Use SET to assign new values.
  • Use WHERE carefully to target specific rows.
  • Combine with calculations or subqueries for powerful updates.

✅ Always double-check your WHERE clause before executing an update to avoid modifying unintended rows.

Share this post:

Comments (0)

No comments yet

Be the first to share your thoughts!

Leave a Comment

0 / 2000

Please be respectful and constructive in your comments.