A group of statements executed within a transaction are
either all executed successfully or none of them is executed.
For example, if a transaction looks like the following:
Now, suppose 2nd statement for delete fails.
If the above group of statements were not enclosed in the transaction, then 1st statement would have been executed without
the other ones below it.
But since the group of statements is enclosed in a transaction, they will either all pass or all fail.
So, for the above case, if 2nd statement (or any statement) fails, the statements before it are also rolled back.
A word of caution: Transactions should be used carefully as they can cause
deadlocks in the system.
Uses: Transactions are required where atomicity of an operation is required.
For example, if A is paying B through a banking account, then receiving of money by B and sending of money by A should either
both happen or should both fail.
If A sends and B does not receive, it would be erroneous.
If A does not send but B receives, then also it would be erroneous.
There is no error only when:
A does not send and B does not receive (Both fail)
A sends and B receives (Both pass)
Got a thought to share or found a bug in the code? We'd love to hear from you: