I D H A M .
Published

Importance of Database Transactions

Authors

2 min read

Database Transactions is one of SQL or DBMS capabilities to manage transaction data flow in a database.

Usually, a database transaction is using if you will manipulate data that involves more than one table.

Conceptually, a transaction will be successful if all transactions in the applied table are successful. When one process fails, must be aborted all transactions.

Must succeed all or if one fails, must fail all.

Let me illustrate with an example.

Two bank customers will transfer funds from one account to another.

The simple flow that will happen is as follows:



Then what if the proccess failure and does not increase the recipient's account balance. At the same time, the balance in the sender's account decreases.



The importance of database transactions is where they can help maintain data consistency in our system.


Database Transaction consists of:

1. Begin Transaction

A statement that will wrap all the code below begin transaction code inside the database transaction.

2. Committ

It's using to notify processes that can save data changes. It should not be missing to commit so that data is stored.

3. Rollback

It's using to cancel all processes wrapped in a transaction database so that data is not stored.


Implementing transaction database with PHP Framework Laravel.

use DB;
DB::startTransaction();
try {
// Line of code to decrease sender's account
#code...
// line of code to increase the recipient's account
#code...
// All processes are successful
// Committed
DB::commit();
} catch (Exception $e) {
// There is a mistake
// Return
DB::return();
}
}

So, this database transaction is essential when involving multiple tables in processing data which is very useful.