How can we use nested transactions allowed in MySQL?



We can allow multiple transactions with the help of START command and SAVEPOINT. Let us create a table with the help of CREATE command.

Creating a table

mysql> CREATE table transactionDemo -> ( -> id int auto_increment, -> primary key(id) -> ); Query OK, 0 rows affected (0.76 sec)

After that, I will begin a transaction with the help of START command −

mysql> START TRANSACTION; Query OK, 0 rows affected (0.00 sec)

After that, I am inserting the following record with the help of INSERT command −

mysql> INSERT into transactionDemo values(); Query OK, 1 row affected (0.04 sec)

We can display a record with the help of SELECT statement, which is as follows −

mysql> SELECT *from transactionDemo; 

The following is the output

+----+ | id | +----+ | 1 | +----+ 1 row in set (0.00 sec)

After that, I am saving this query with the help of SAVEPOINT. The query is as follows −

mysql> SAVEPOINT t2; 

Insert record

mysql> INSERT into transactionDemo values(); Query OK, 1 row affected (0.00 sec)

Display all the records with the help of SELECT command −

mysql> SELECT *from transactionDemo; 

The following is the output

+----+ | id | +----+ | 1 | | 2 | +----+ 2 rows in set (0.00 sec)

Now, we can rollback the first transaction −

mysql> ROLLBACK TO t2; Query OK, 0 rows affected (0.03 sec)

Now, we can display the transaction saved previously −

mysql> SELECT * from transactionDemo; 

The following is the output

+----+ | id | +----+ | 1 | +----+ 1 row in set (0.00 sec)
Updated on: 2020-06-25T08:11:48+05:30

485 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements