๐Ÿ“˜ What is TCL (Transaction Control Language)?

TCL (Transaction Control Language) is the part of SQL used to manage transactions โ€” a group of operations that should either all happen together or none at all.

Think of TCL as the safety switch in SQL. It makes sure your database doesnโ€™t end up in a half-updated, broken state.


๐Ÿงฉ First, Whatโ€™s a Transaction?

A transaction is a single unit of work that may include multiple DML operations (e.g., INSERT, UPDATE, DELETE) โ€” and it should be atomic, i.e., either all of it happens, or none of it does.

Example use case: Transferring money from account A to B.

-- Step 1: Withdraw from A
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
 
-- Step 2: Deposit to B
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';

If step 1 happens but step 2 fails, the money disappears. Thatโ€™s where TCL saves you.


๐Ÿ› ๏ธ Key TCL Commands:

CommandPurpose
BEGIN / START TRANSACTIONMarks the beginning of a transaction
COMMITSaves all changes made during the transaction
ROLLBACKCancels all changes made during the transaction
SAVEPOINTSets a checkpoint inside a transaction so you can partially rollback
RELEASE SAVEPOINTDeletes a savepoint so it canโ€™t be rolled back to
SET TRANSACTIONSets isolation level for consistency vs performance trade-offs

๐Ÿ” Example Flow:

BEGIN;
 
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
 
COMMIT; -- permanently saves both operations

If something fails before COMMIT:

 
ROLLBACK; -- cancels both updates

๐Ÿ“Œ SAVEPOINT Example:

BEGIN;
UPDATE users SET status = 'inactive' WHERE id = 1;
SAVEPOINT before_delete;
DELETE FROM users WHERE id = 2;
ROLLBACK TO before_delete;
COMMIT;

Only the delete is undone; the status update remains.


๐Ÿ”’ Transactions Must Follow ACID:

PropertyMeaning
AtomicityAll or nothing
ConsistencyData must remain valid before and after the transaction
IsolationTransactions donโ€™t interfere with each other
DurabilityOnce committed, changes persist even if the system crashes

๐Ÿง  Interview Line:

โ€œTCL manages transactions using commands like COMMIT, ROLLBACK, and SAVEPOINT to ensure data consistency and atomicity โ€” crucial for operations that must succeed or fail as a whole.โ€