Using MySQL ROLLBACK to Handle Transaction Errors
Rollback a Transaction on Error
Write a MySQL query to start a transaction, attempt to update a column, and rollback the changes if an error occurs.
Solution:
Explanation:
- Purpose of the Query:
- The goal is to demonstrate how to undo changes if an error occurs during a transaction.
- This shows the use of ROLLBACK.
- Key Components:
- START TRANSACTION: Begins a new transaction.
- UPDATE Employees: Attempts to update salaries.
- ROLLBACK: Undoes the changes if an error occurs.
- Why use Transactions?:
- Rollback ensures that incomplete or erroneous changes are not applied to the database.
- Real-World Application:
- For example, in an e-commerce system, you might rollback a transaction if inventory updates fail during an order placement.
For more Practice: Solve these Related Problems:
- Write a MySQL query to update a column and rollback the changes if the new value exceeds a certain limit.
- Write a MySQL query to delete a record and rollback if a foreign key constraint violation occurs.
- Write a MySQL query to insert a record into two tables within a transaction and rollback if the second insertion fails.
- Write a MySQL query to attempt a division operation and rollback if a division by zero error occurs.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous MySQL Exercise: Start a Transaction and Commit Changes.
Next MySQL Exercise: Set Isolation Level to Read Committed.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.