Lesson 1 · Unit 03
All or nothing
BEGIN, COMMIT, ROLLBACK and the four ACID promises
What you practise
BEGIN,COMMIT,ROLLBACK- Atomicity, consistency, isolation, durability with a money-transfer example
- Constraints as the last line of defence
Try a question from this lesson
Pick one
Moving 30 from Ana to Bo takes two statements. The server dies right after the first, and no transaction surrounds them. What is in the table after the restart?
CREATE TABLE accounts(name, balance);
INSERT INTO accounts VALUES
('Ana', 100), ('Bo', 50);
UPDATE accounts SET balance =
balance - 30 WHERE name = 'Ana';
UPDATE accounts SET balance =
balance + 30 WHERE name = 'Bo';Correct answer
Ana 70, Bo 50: 30 has vanished
Why
Each statement on its own is permanent the moment it finishes. The first one finished; the second never ran. The bank is now 30 short, and nothing in the data says why.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A transaction is all or nothing
BEGIN starts a transaction. Nothing you change is final until COMMIT, which makes all of it permanent at once. ROLLBACK throws all of it away instead.
If the server crashes before the COMMIT, the half-done work is rolled back on restart. Either both updates happen, or neither.
CREATE TABLE accounts(name, balance);
INSERT INTO accounts VALUES
('Ana', 100), ('Bo', 50);
BEGIN;
UPDATE accounts SET balance =
balance - 30 WHERE name = 'Ana';
UPDATE accounts SET balance =
balance + 30 WHERE name = 'Bo';
COMMIT;Concept
Constraints: the last line of defence
A constraint is a rule the database enforces on every write, whatever the application does.
CHECK (balance >= 0) refuses any statement that would leave a negative balance. NOT NULL, UNIQUE and foreign keys work the same way.
A refused statement raises an error. The usual response is to roll the transaction back.
CREATE TABLE accounts(
name TEXT PRIMARY KEY,
balance INT NOT NULL
CHECK (balance >= 0));9 more exercises in the app
- 3× type the answer
- 1× fill the blanks
- 1× match the pairs
- 2× multiple choice
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.