Database.Beginner.What is a transaction?

What is a Transaction in SQL?

A transaction is a single unit of work that consists of one or more SQL statements, executed together as a group.

  • The database treats a transaction as all or nothing:
    • All statements succeed ➔ transaction is committed (saved permanently).
    • Any statement fails ➔ transaction is rolled back (undone completely).

Think of a transaction like a package deal — either the whole deal goes through, or none of it does.

Key Properties of a Transaction

(These are the ACID properties we talked about earlier.)

PropertyMeaning
AtomicityAll or nothing — no partial changes.
ConsistencyDatabase must move from one valid state to another.
IsolationTransactions don’t interfere with each other.
DurabilityOnce committed, the changes are permanent.

Typical Transaction Commands

CommandWhat It Does
BEGIN or START TRANSACTIONStart a new transaction.
COMMITSave all changes made in the transaction.
ROLLBACKUndo all changes if something goes wrong.

Example

Let’s say you’re transferring money between two accounts:

START TRANSACTION;

UPDATE Accounts SET balance = balance - 100 WHERE account_id = 1;  -- Debit
UPDATE Accounts SET balance = balance + 100 WHERE account_id = 2;  -- Credit

COMMIT;

If both updates succeed: the transaction is committed — money moves.

If anything fails (e.g., system crash in the middle): the transaction can ROLLBACK — no money is moved.

Why Use Transactions?

  • To ensure data integrity.
  • To group multiple steps into a single, safe operation.
  • To recover safely if something fails.
  • To avoid partial updates (e.g., one account debited but the other not credited).

Real-Life Analogy

Buying an item online:

  • Deduct payment from your account.
  • Create an order record.
  • Reduce inventory.
  • Confirm shipment.

✅ Either all of this happens, or none of it happensno half-bought products!

In Short

A transaction is a set of operations that must all succeed together or fail together — ensuring the database stays reliable and consistent.

This entry was posted in Без рубрики. Bookmark the permalink.