Structured Query Language/COMMIT and ROLLBACK

DBMS offers a special service. We can undo a single or even multiple consecutive write and delete operations. To do so, we use the command ROLLBACK. When modifying data, the DBMS writes in a first step all new, changed, or deleted data to a temporary space. During this stage, the modified data is not part of the 'regular' database. If we are sure the modifications shall apply, we use the COMMIT command. If we want to revert our changes, we use the ROLLBACK command. All changes up to the finally COMMIT or ROLLBACK are considered to be part of a so-called transaction.

The syntax of COMMIT and ROLLBACK is very simple. The keyword 'WORK' is optional.

Work without AUTOCOMMIT
The feature AUTOCOMMIT automatically performs a COMMIT after every write operation (INSERT, UPDATE, or DELETE). This feature is not part of the SQL standard, but is implemented and activated by default in some implementations. If we want to use the ROLLBACK command, we must deactivate the AUTOCOMMIT. (After an - automatic or explicit - COMMIT command, a ROLLBACK command is syntactically okay, but it does nothing as everything is already committed.) Often we can deactivate the AUTOCOMMIT with a separate command like 'SET autocommit = 0;' or 'SET autocommit off;' or by clicking an icon on a GUI.

To test the following statements, it's necessary to work without AUTOCOMMIT.

COMMIT
Let us insert a new person into the database and test the COMMIT.

Now we remove the person from the database.

So far, so boring.

ROLLBACK
The exciting command is the ROLLBACK. It restores changes of previous INSERT, UPDATE or DELETE commands.

We delete and restore Mrs. Hamilton from our example database.

The ROLLBACK is not restricted to one single row. It may affect several rows, several commands, different kinds of commands, and even several tables.

Exercises
Supose the hobby table contains 9 rows and the person table 10 rows. We execute the following operations:

add 3 hobbies

add 4 persons

commit

add 5 hobbies

add 6 persons

rollback

How many rows are in the hobby table?

How many rows are in the person table?