ROLLBACK
ROLLBACK is a SQL command used to undo transactions that have not already been saved to the database. The command reverses all recent changes that are not yet committed to the system. It is an essential command when it comes to managing the control flow of the SQL database, safeguarding against unwanted modifications or errors.
Example
Output
Explanation
In the example, initially a transaction is started with the START TRANSACTION
statement. An UPDATE
statement is issued to increase the salary of an employee with the employee id of 1 by 100. However, the ROLLBACK
statement is called immediately after which undoes the changes made by the UPDATE
statement. Therefore, when the data is fetched, the salary of the employee with the id of 1 remains as it was prior to the UPDATE
, hence displaying its original value.
Example
Output
- Example from SELECT * FROM employees before the ROLLBACK;
- Example from SELECT * FROM employees after the ROLLBACK;
Explanation
In the provided code example, first, a new transaction is begun with the BEGIN
command. Then, an INSERT
operation is performed to add a new employee record. A SELECT
operation shows the table content after the insertion.
The ROLLBACK
command is used to undo the operations performed within the current transaction. Therefore, the output after the ROLLBACK
doesn’t include the recently inserted record which means John Doe has been removed from the list. Thus, it illustrates the SQL ROLLBACK
operation’s ability to revert changes made within a transaction.
Example
Output
No output will be generated as the transaction is rolled back.
Explanation
The ROLLBACK command in SQL is used to undo transactions that have not yet been saved to the database. The ROLLBACK command can also be used to undo a GROUP of transactions. In this example, the “INSERT INTO” transaction is cancelled using the ROLLBACK command. Thus, the new row is not inserted into the “Customers” table.
Example
Output
No output is displayed for this transaction. The ROLLBACK statement undoes a transaction without providing a confirmation message.
Explanation
In this example, a savepoint named ‘save_pt’ is defined. A new record is inserted into the ‘employee’ table. Then, the ROLLBACK TO statement is used to undo the changes made after the savepoint ‘save_pt’. The COMMIT statement is used to end the transaction. The record inserted into the ‘employee’ table is not saved due to the ROLLBACK TO statement.
Example
Output
Explanation
The ROLLBACK command undoes all changes made during the current transaction. In the example, ‘John Doe’ was inserted into the ‘employees’ table. But because the ROLLBACK command was issued, that change was discarded and ‘John Doe’ was not in the ‘employees’ table when it was queried again.