Introduction to Database Transaction
source link: https://dev.to/milhamh95/introduction-to-database-transaction-52nm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Introduction to Database Transaction
Apr 10 Originally published at milhamh.dev
・2 min read
Database Transaction
Database transaction is a collection of multiple database operations (ex: SELECT
, UPDATE
, DELETE
, or INSERT
) as a single unit of work. It represent real-world events of any company. Error handling becomes much simple for an application when using transactions.
We can define where the transaction will begin and when the transaction will end. To start the transaction we use BEGIN
syntax.
If queries in a transaction ran successfully, then we save the changes using COMMIT
syntax. If queries in a transaction failed to run, then we revert the changes before the transaction ran using ROLLBACK
syntax.
Now, let's see the example of a transaction.
Example
Alice wants to transfer $100 to John. In the database, ACCOUNT
table stored Alice and John account data.
In a transaction, the operations are:
// Select Alice account data
// Check the balance
SELECT BALANCE FROM ACCOUNT WHERE ID = 1
// Substract 100 from Alice balance
UPDATE ACCOUNT SET BALANCE = BALANCE - 100 WHERE ID = 1
// Add 100 to Alice balance
UPDATE ACCOUNT SET BALANCE = BALANCE + 100 WHERE ID = 2
If the operations was success, then we have to commit the transaction using COMMIT
If one of the operations was failed, then we have to rollback the transaction using ROLLBACK
Sources
Wangde - A Deep Dive into Database Concurrency Control
Pulkit Gupta - System Design: Database Transactions & ACID compliance (Part 1)
Adam Edelweiss - Relational Database 10 | Database Transaction
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK