SQL Tutorial



UPDATE QUERY


UPDATE Query in SQL

The UPDATE statement in SQL is used to modify the existing records in a table. It’s part of Data Manipulation Language (DML) and allows you to update one or more fields in a table.

πŸ“ Basic Syntax

Here’s the basic syntax of the UPDATE query:

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

Explanation: The SET keyword is used to specify the column(s) to be updated, and the WHERE clause ensures that only the rows matching the condition are updated. If you omit the WHERE clause, all rows in the table will be updated, which might not be what you intend.

πŸ’‘ Example 1: Update a Single Record

Let’s say we have a table called Employees with columns EmployeeID, EmployeeName, and Department.

-- Updating the department of an employee
UPDATE Employees
SET Department = 'Finance'
WHERE EmployeeID = 1;
  

This statement updates the department of the employee with EmployeeID 1 to "Finance".

πŸ’‘ Example 2: Update Multiple Records

You can also update multiple records at once by using a condition in the WHERE clause that matches multiple rows.

-- Updating the department for multiple employees
UPDATE Employees
SET Department = 'Sales'
WHERE EmployeeID IN (2, 3, 4);
  

This statement updates the department of employees with EmployeeID 2, 3, and 4 to "Sales".

πŸš€ Try It Out!

Let's test your understanding of the UPDATE query. You’re managing a Books table, and the columns are:

  • BookID: Unique identifier for the book
  • BookTitle: Title of the book
  • Author: Author of the book
  • Price: Price of the book

Your task is to update the price of the book titled "The Great Adventure" to 22.99.

Write the UPDATE statement below:

πŸ’‘ What to Remember:

  • WHERE Clause: The WHERE clause is essential to target specific rows. If omitted, all rows will be updated.
  • Multiple Columns: You can update multiple columns in one statement by separating them with commas.
  • Data Types: Ensure that the data types of the new values match the column types (e.g., numbers for numeric columns, strings for text columns).

Conclusion

The UPDATE statement is a powerful tool for modifying data in your database. By specifying the correct condition in the WHERE clause, you can update one or multiple records with ease!

Quick Tip:

Always test your UPDATE queries with a WHERE condition before running them on a live database to avoid accidental updates!


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review