How to Update a Single Record in SQL Based on a Condition?
Update a Single Record
Write a SQL query to update a single record in a table based on a specific condition.
Solution:
-- Update the salary of an employee with EmployeeID = 1.
UPDATE Employees -- Specify the table to update.
SET Salary = 55000 -- Set the new value for the "Salary" column.
WHERE EmployeeID = 1; -- Apply the update only to the employee with ID 1.
Explanation:
- The goal is to update the Salary of a specific employee in the Employees table.
- This demonstrates how to use the UPDATE statement to modify existing data in a table based on a condition.
- UPDATE Employees : Specifies the table where the update will occur.
- SET Salary = 55000 : Defines the new value for the Salary column.
- WHERE EmployeeID = 1 : Ensures that the update applies only to the employee with EmployeeID = 1.
- The UPDATE statement is used to modify existing records in a table, making it essential for maintaining accurate and up-to-date data.
- For example, if an employee receives a raise, their salary can be updated in the database using this statement.
- For example, in a company database, you might use this query to update the salary of an employee with EmployeeID = 1 to reflect a recent promotion or adjustment.
1. Purpose of the Query :
2. Key Components :
3. Why use UPDATE? :
4. Real-World Application :
Additional Notes:
- WHERE clause is critical to ensure that updates are applied only to the intended rows.
- Scenarios where updating a single record is appropriate, such as:
- Adjusting an employee's salary after a promotion or raise.
- Correcting erroneous data in a specific record.
- Important Considerations :
- Always include a WHERE clause to avoid unintentionally updating all rows in the table.
- Verify that the condition in the WHERE clause uniquely identifies the target record.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous SQL Exercise: Insert Multiple Records
Next SQL Exercise: Update Multiple Records.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics