TechnicalMedium SQL & Databases
What is a database transaction and what does ACID mean?
Asked for Backend Developer, Full-Stack Developer
Why they ask this: Payments and orders must never be half-saved; this checks you can protect data consistency.
Answer
A transaction groups several statements so that they all succeed or all fail together.
ACID:
- Atomicity: all or nothing. On error, everything is rolled back.
- Consistency: the data moves from one valid state to another and constraints still hold.
- Isolation: concurrent transactions do not see each other's half-finished work (the exact level depends on the isolation level).
- Durability: once committed, the data survives a crash.
php
DB::transaction(function () use ($order, $payment) {
$payment->update(['status' => 'paid']);
$order->update(['status' => 'confirmed']);
$order->product->decrement('stock', $order->quantity);
}); // any exception rolls back all threeClassic example: a bank transfer debits one account and credits another. Both must happen, or neither.
Can you explain this in your own words?