Chuyển đến nội dung chính
eLearner.app
Mô-đun 11 · Bài học 1 trong tổng số 441/57 trong khóa học~15 min
Bài học theo mô-đun (1/4)

Giao dịch ACID (BEGIN/COMMIT)

The foundations of reliability for any database rest on the ACID acronym:

  • Atomicity: an operation either completes entirely (Commit), or fails leaving no half-done traces behind (Rollback).
  • Consistency: the database rules (e.g. constraints, Foreign Keys) are always respected.
  • Isolation: transactions happening at the same time don't interfere with each other in uncontrolled ways.
  • Durability: after a Commit, the change is irreversibly written to disk.

Transaction syntax

Normally each single UPDATE or DELETE query is treated as a standalone transaction (autocommit). But when you want to group multiple operations together, for example debiting the customer's account and placing the order, you have to do it explicitly using transaction syntax.

SQL
BEGIN;

UPDATE accounts SET balance = balance - 100 WHERE user_id = 1;
INSERT INTO orders (user_id, total) VALUES (1, 100);

COMMIT; -- Writes the changes

If during these complex executions the JavaScript app that sent the query realizes there's a problem (for example there isn't enough stock in the warehouse and it crashes), it would send a:

SQL
ROLLBACK; -- Cancels the changes and discards the 2 queries sent in the block

Try it yourself

tập thể dục#sql.m11.l1.e1
Nỗ lực: 0Đang tải…

Open a transaction.\nUpdate the product with ID 10 setting its 'quantity' to 0 in the temporary table (no wait, 'quantity' isn't on products, let's invent: change 'unit_price' in 'order_items' but that requires a constraint.\nLet's do better: Update the status of order ID 5 to 'shipped' and successfully complete the transaction.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Start with BEGIN;, change orders for id = 5 to status='shipped', then send it with COMMIT;

Giải pháp khả dụng sau 3 lần thử

tập thể dục#sql.m11.l1.e2
Nỗ lực: 0Đang tải…

Panic in production! A dev wrote a DELETE without the WHERE, historically wiping all the reviews.\nLet's show them how rollback is done. Start a transaction, fire off a quick DELETE that wipes everything from 'reviews' (without a WHERE clause), but then use the SQL lifesaver to undo the impact before completing the block.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

BEGIN;, the clean-slate delete on 'reviews', and then the magic ROLLBACK; at the end.

Giải pháp khả dụng sau 3 lần thử