DEV Community

Cover image for What is database transaction?
Shrikanta Mazumder
Shrikanta Mazumder

Posted on

What is database transaction?

Database transaction is a set of queries treated as one unit of work.

Transaction Lifespan:
A transaction begins with BEGIN keyword. It says to the database that you are about to start a new transaction with multiple queries. Then you can write queries (1,2,… whatever you need), and when each query executes successfully and you are satisfied you should commit it by using the COMMIT keyword. This commit tells the database that the changes I have done during the whole lifespan of the transaction, persist these things in the disk.
But things can necessarily go wrong. Maybe one of your queries is not executed properly or you are not satisfied, then you should forget about all the changes you have done before this query during the transaction lifetime. The ROLLBACK helps to undo or roll back all changes.

Two types of database transactions:
Explicit Transaction: You should define the transaction boundary explicitly with BEGIN keyword, and COMMIT after execution. ROLLBACK for unsatisfied cases.

BEGIN tx1
Query1….
Query2….
……
COMMIT tx1
Or
ROLLBACK tx1 (if something is wrong)
Enter fullscreen mode Exit fullscreen mode

Implicit Transaction: The implicit transaction begins before the statement is executed and ends (commit or rollback) after the statement is executed.

// one transaction
BEGIN tx1
Query1….
COMMIT tx1
ROLLBACK tx1 (if something is wrong)

//another transaction
BEGIN tx2
Query1….
COMMIT tx2
ROLLBACK tx2 (if something is wrong)
Enter fullscreen mode Exit fullscreen mode

If you run queries without explicitly transaction boundary every time an implicit transaction wraps around every individual statement to save the changes to DB. For example, Alice wants to send $100 to Bob, and your first query deducted $100 from Alice's account successfully, but something went wrong when you tried to credit/update it in Bob's account. In this scenario, $100 is lost in space (maybe it can handle it in a tricky way), and you should again undo all queries that executed successfully. But with an explicit transaction, until your queries execute successfully and the execution of COMMIT, it won't save in DB. If get something wrong in the query execution, ROLLBACK will undo everything by itself. There is no need to consider which one has changed or not.

A transaction could change data, or it could be read-only as well.

Top comments (0)