πΉ What is a Transaction?
A transaction is a sequence of one or more SQL statements executed as a single unit of work.
It ensures the ACID properties:
- Atomicity β all or nothing
- Consistency β maintains data integrity
- Isolation β transactions donβt interfere with each other
- Durability β once committed, changes are permanent
πΉ Transaction Control Commands
- BEGIN / START TRANSACTION β starts a new transaction.
- COMMIT β saves all changes made in the transaction permanently.
- ROLLBACK β undoes all changes made in the current transaction.
πΉ Example Scenario
Letβs say we have a bank_accounts
table:
CREATE TABLE bank_accounts (
account_id INT PRIMARY KEY,
account_name VARCHAR(50),
balance DECIMAL(10,2)
);
INSERT INTO bank_accounts VALUES (1, 'Alice', 1000.00);
INSERT INTO bank_accounts VALUES (2, 'Bob', 500.00);
β Successful Transaction (COMMIT)
Alice transfers 200 to Bob:
BEGIN;
UPDATE bank_accounts
SET balance = balance - 200
WHERE account_id = 1; -- Alice
UPDATE bank_accounts
SET balance = balance + 200
WHERE account_id = 2; -- Bob
COMMIT;
β‘ Both updates are applied permanently.
β Failed Transaction (ROLLBACK)
Alice tries to transfer 2000 (more than her balance):
BEGIN;
UPDATE bank_accounts
SET balance = balance - 2000
WHERE account_id = 1; -- Alice (now -1000, invalid)
UPDATE bank_accounts
SET balance = balance + 2000
WHERE account_id = 2; -- Bob
ROLLBACK;
β‘ Both updates are undone, balances stay unchanged.
πΉ Key Notes
- Many databases (PostgreSQL, MySQL with InnoDB, Oracle, SQL Server) support transactions.
- Some operations (like
CREATE TABLE
) auto-commit and canβt be rolled back. - You can also use SAVEPOINT to roll back partially within a transaction.