A transaction is a unit of work done against the database in a logical sequence. The sequence is extremely important in a transaction.
It is a logical unit of work that contains one or more SQL statements. The result of all these statements in a transaction either gets completed successfully (all the changes made to the database are permanent) or if at any point any failure happens it gets rollbacked (all the changes being done are undone).
Consider an ATM or online system with a total balance of ₹3000 across two accounts in a bank: Account A (₹1000) and Account B (₹2000). Let's perform a single transaction (Task 1): transferring ₹50 from Account A to Account B.
T1: Transfer ₹50
1 read(A);
2 A := A - 50;
3 write(A);
4 read(B);
5 B := B + 50;
6 write(B);
These 6 steps are considered collectively as a single, atomic task. Either all 6 steps execute successfully, meaning the ₹50 is deducted from A and correctly added to B, or none of them do.
If a failure occurs right after step 3, Account A has ₹950 but Account B still has ₹2000. In this case, the transaction rolls back to fix the inconsistency.
To ensure integrity of the data, we require that the database system maintain the following properties of the transaction.
Either all operations of a transaction are reflected properly in the DB, or none are. (All or nothing).
Integrity constraints must be maintained before and after the transaction. DB must be consistent after transaction happens.
Even though multiple transactions may execute concurrently, each transaction is unaware of other transactions. Multiple transactions can happen in isolation, without interfering with each other.
After a transaction completes successfully, the changes it has made to the database persist, even if there are system failures.
The very first state of the life cycle of the transaction, all the read and write operations are being performed here. If they execute without any error the T comes to Partially committed state. Although if any error occurs then it leads to a Failed state.
After transaction is executed the changes are saved in the buffer in the main memory. If the changes made are permanent on the DB then the state will transfer to the committed state and if there is any failure, the T will go to Failed state.
When updates are made permanent on the DB. Then the T is said to be in the committed state. Rollback can't be done from the committed state. New consistent state is achieved at this stage.
When T is being executed and some failure occurs. Due to this it is impossible to continue the execution of the T.
When T reaches the failed state, all the changes made in the buffer are reversed. After that the T rollback completely. T reaches abort state after rollback. DB's state prior to the T is achieved.
A transaction is said to have terminated if it has either committed or aborted.