Database.What is a “transaction”?

💼 What is a Transaction in a Database?

A transaction is a sequence of one or more SQL operations (such as INSERT, UPDATE, DELETE) that are executed as a single logical unit of work.

A transaction must either complete fully or have no effect at all — there is no in-between.


🔒 Transactions follow the ACID properties:

PropertyMeaning
A – AtomicityAll operations succeed or none do — it’s all-or-nothing
C – ConsistencyThe database remains in a valid state before and after the transaction
I – IsolationTransactions are isolated from each other while running
D – DurabilityOnce committed, the changes are permanent (even after crash)

🛠️ Example:

BEGIN;

UPDATE Accounts SET balance = balance - 100 WHERE id = 1;
UPDATE Accounts SET balance = balance + 100 WHERE id = 2;

COMMIT;

✅ If both updates succeed: COMMIT makes them permanent

❌ If any fails: ROLLBACK undoes all changes

🔄 Commands:

CommandDescription
BEGIN / START TRANSACTIONStarts a new transaction
COMMITSaves all changes
ROLLBACKCancels all changes since BEGIN

🔍 Why Use Transactions?

  • To transfer money safely between accounts
  • To batch multiple operations that must succeed together
  • To maintain data integrity in case of errors or crashes
This entry was posted in Без рубрики. Bookmark the permalink.