The concept of transaction in the database is an important concept that all programmers should know because we will work a lot with this concept. In this article, I would like to talk to you about this concept!
For the sake of illustration, let’s take the following example: we are working on a bank application, which has a feature that transfers money between bank accounts, from account A to account B. This is a feature that the process will take two steps:
- First, subtract the money from account A.
- And the second step is add money to account B.
Obviously, as you can see, this is a process that if successful is required, the above two steps must be successful, or fail if two failures are required. If only one of the two succeeds or fails, then we are in trouble right away. And when building the application must also ensure the above two conditions.
This is the main idea of the transaction concept in the database. In a database, a transaction is a set of operations where either the operation is successful, or no successful operation is performed. When you think about transactions in the database, imagine it is “either all or nothing”.
Here, we have an ACID acronym (Atomicity, Consistency, Isolation, Durability) defining the properties of a transaction in the database.
- Atomicity: this property expresses the concept of “either all or nothing”. All steps taken in a transaction, if successful, must succeed all; if all fail, then all must fail. If a transaction succeeds then all changes must be saved to the database. If it fails then all changes in that transaction must be rolled back to its original state.
In my example, it is obvious that when the money in account A is deducted, it is necessary to add money to account B. Otherwise, nothing happens, did not deduct money in account A then surely, the money into account B also did not happen.
- Consistency: Data from the start transaction time to the end should be consistent.
In my example, if you subtract 10$ in account A, then in account B must be plus 10$.
- Isolation: If we have multiple transactions at the same time, we must ensure that these transactions occur independently, without affecting each other on the data.
In our example, assuming the same transaction occurs at the same time, we obviously do not determine the status of account A and account B after the implementation of the same time, which is very dangerous.
- Durability: This means that the data after the transaction will not change if we encounter a problem related to the database.
For example, after transferring money to account B successfully, even if the database has any problems, account B is still guaranteed to have received 10$.