Skip to content
BENIBIX Learn

Database Transaction

Development🗃️ DatabasesRelational Databases

Also known as Transaction, SQL Transaction

A group of changes that all happen, or none of them do.

Think of it like

Think of it like a card swap with a friend. You both hand a card over, or no one does.

Example

Emma moves 30 euros from her account to Jack's. The app takes it from her and adds it to him in one transaction, so it can never vanish halfway.

Why it matters

If a crash comes in the middle of a task, the data is left broken. Transactions stop that.

Definition

A transaction is a group of database changes that work or fail as one. You start it, make some changes, then COMMIT to keep them all. If something goes wrong, a ROLLBACK undoes each change in the group. This stops half-done work, like money that leaves one account but never reaches the other. All the big SQL databases support them.

Example code

sql
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE name = 'Emma';
ROLLBACK;
SELECT * FROM accounts;
-- Emma | 100
-- Jack | 50
The rollback undoes the change, so Emma still has 100.

Common mistake

Keeping a transaction open while waiting for a user or a slow API. It locks rows and blocks everyone else.

Key takeaways

  1. 1
    All or nothing. Every change or none.
  2. 2
    Commit or roll back. Keep it all, or undo it all.
  3. 3
    Keep it short. Long ones block others.