Bitpath

Lesson 1 · Unit 03

All or nothing

BEGIN, COMMIT, ROLLBACK and the four ACID promises

12 exercisesabout 3 min

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?

SQL
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';

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.

SQL
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.

SQL
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.

One email when Bitpath is ready to try. Nothing else. Privacy