SQL Transactions
SQL Transactions
Topperworld.in
Transactions
❖ Properties of Transaction
Transactions have the following four standard properties, usually referred
to by the acronym ACID.
• Atomicity: The outcome of a transaction can either be completely
successful or completely unsuccessful. The whole transaction must be
rolled back if one part of it fails.
• Consistency: Transactions maintain integrity restrictions by moving the
database from one valid state to another.
• Isolation: Concurrent transactions are isolated from one another,
assuring the accuracy of the data.
• Durability: Once a transaction is committed, its modifications remain in
effect even in the event of a system failure.
©Topperworld
SQL
Syntax:
BEGIN TRANSACTION
transaction_name ;
✓ The values for the properties of the current transaction, such as the
transaction isolation level and access mode, are set using the SET
TRANSACTION Statement in MySQL.
Syntax:
SET TRANSACTION [ READ WRITE | READ
ONLY ];
©Topperworld
SQL
• COMMIT Command
✓ The COMMIT command saves all the transactions to the database since
the last COMMIT or ROLLBACK command.
Syntax:
COMMIT;
Example:
Sample Table1
Following is an example which would delete those records from the table
which have age = 20 and then COMMIT the changes in the database.
Query:
DELETE FROM Student WHERE AGE = 20;
COMMIT;
©Topperworld
SQL
Output:
Thus, two rows from the table would be deleted and the SELECT statement
would look like,
• ROLLBACK Command
✓ If any error occurs with any of the SQL grouped statements, all changes
need to be aborted.
✓ This command can only be used to undo transactions since the last
COMMIT or ROLLBACK command was issued.
ROLLBACK;
Example:
©Topperworld
SQL
Query:
Output:
• SAVEPOINT Command
SAVEPOINT
SAVEPOINT_NAME;
©Topperworld
SQL
✓ This command is used only in the creation of SAVEPOINT among all the
transactions.
ROLLBACK TO
SAVEPOINT_NAME;
Example:
From the above example Sample table1, Delete those records from the table
which have age = 20 and then ROLLBACK the changes in the database by
keeping Savepoints.
Query:
SAVEPOINT SP1;
//Savepoint created.
DELETE FROM Student WHERE AGE = 20;
//deleted
SAVEPOINT SP2;
//Savepoint created.
Here SP1 is first SAVEPOINT created before deletion.In this example one
deletion have taken place.
After deletion again SAVEPOINT SP2 is created.
©Topperworld
SQL
Output:
Deletion have been taken place, let us assume that you have changed your
mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP1
which is before deletion.
deletion is undone by this statement.
Query:
ROLLBACK TO SP1;
//Rollback completed
Output:
©Topperworld
SQL
Syntax:
RELEASE SAVEPOINT
SAVEPOINT_NAME
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK
command to undo transactions performed since the last SAVEPOINT.
It is used to initiate a database transaction and used to specify characteristics
of the transaction that follows.
©Topperworld