DEV Community

Muhammad Wasi Naseer
Muhammad Wasi Naseer

Posted on • Updated on

Transaction in Database

A transaction is a unit of work that must maintain ACID properties. ACID is an acronym of Atomicity, Consistency, Isolation, and Durability

Let’s look at each of them in detail.

Atomicity

A transaction contains a query or a set of queries. In order to maintain atomicity property, the transaction either has to execute all the queries or none of them. In short, all the queries will be treated as atomic. If any of the queries fails, the transaction has to roll back all the previous executed queries.

Consistency

First, let’s understand what a consistent state means in a database. A database is in a consistent state if it follows all the rules defined using constraints, triggers, or cascades.

A transaction must always lead the database to a consistent state.

For example, if a table user has a unique constraint on the national_id column and a query in my transaction tries to insert the duplicate national_id, the query has to be failed. Otherwise, the database will not be in a consistent state as it will violate the unique constraint on our user table.

Isolation

All transactions must be executed independently of other transactions. Each transaction will be executed as if it’s the only transaction executed in the database.

There are multiple levels of isolation levels that we can define in a database. We have discussed them in detail in our this article.

Durability

If a transaction commits data, it must be able to persist them even if the system fails or restart. In short, committed transactions means the data has been persisted, and if it’s not able to save the data due to system failure, it must persist at the system start.

Top comments (0)