Transactions and Design Review
Use transactions and the ACID properties to keep data correct when many users write at once, and review a schema with a practical checklist.
Welcome back!
Step 1 of 13Learn
All or nothing
A customer buys the last copy of a book. The application must do three things: insert the order, insert the order line, and reduce the stock count by one. What if the server crashes after the first two steps? The order exists, but stock still shows one copy, so another customer buys the same book.
A transaction groups several statements into a single unit of work that either completes entirely or not at all:
BEGIN;
INSERT INTO orders (order_id, order_date, customer_id) VALUES (9001, CURRENT_DATE, 7);
INSERT INTO order_line (order_id, book_id, quantity, unit_price) VALUES (9001, 42, 1, 18.50);
UPDATE book SET stock = stock - 1 WHERE book_id = 42;
COMMIT;If anything fails before COMMIT, whether a constraint violation, a crash or an explicit ROLLBACK, the database undoes every statement in the transaction, as if none had run. The data moves from one valid state to another valid state, never stopping in a half-finished one.
Designers care about transactions because they define which rules can be trusted. "Every order has at least one line" can't be enforced by a single constraint, but inserting the order and its first line in one transaction makes it hold in practice.
Step 2 of 13Practice · True or false
If the third statement of a four-statement transaction fails and the transaction is rolled back, the effects of the first two statements remain in the database.
Step 3 of 13Practice · Diagram
Selling the last copy as one transaction
Tap the step that must finish before the sale is safe from a crash.
Tap the shape that answers the question, then press Check.
- BEGIN
- Insert the order
- Insert the order line
- Reduce stock by one
A CHECK (stock >= 0) here would reject a sale that oversells.
- COMMIT
Only now do all three changes become visible and permanent together.
Step 4 of 13Learn
ACID
Transactions in relational databases provide four guarantees, summarized as ACID:
- Atomicity: all statements in a transaction take effect, or none do.
- Consistency: a transaction moves the database from one valid state to another; every constraint (keys, foreign keys, CHECKs) holds after commit.
- Isolation: concurrent transactions don't see each other's unfinished work; the result is as if they had run in some order, to a degree set by the isolation level.
- Durability: once committed, changes survive crashes and power loss, typically because they are first written to a log on disk.
These guarantees are a big part of why relational databases dominate systems that handle money, inventory and bookings. Some distributed NoSQL systems relax them, for example offering eventual consistency, where replicas may briefly disagree, in exchange for scale and availability. That's a reasonable trade for a social media like counter and a poor one for a bank balance.
Notice how design and ACID work together. Consistency only means as much as the constraints you declared. A database without foreign keys or CHECK constraints can commit perfectly "consistent" transactions full of nonsense, because it has no rules to check against.
Step 5 of 13Practice · Match the pairs
Match each ACID property to the situation it protects against.
Tap an answer, then tap the place where it belongs (or drag it there).
- Atomicity
- Consistency
- Isolation
- Durability
Step 6 of 13Diagram
ACID, one guarantee per letter
Tap a shape with to see more.
- Transaction
- Atomicity
All statements or none: no half-finished orders.
- Consistency
Every constraint holds before and after.
- Isolation
Concurrent transactions do not see each other’s half-done work.
- Durability
Committed changes survive crashes and power cuts.
Step 7 of 13Learn
Concurrency: when users collide
Isolation matters because real systems run many transactions at once. Two classic problems show why.
Lost update. Two clerks read the stock of a book: 5. Each sells one copy and writes back 4. The stock should be 3, but it's 4: one sale vanished. The fix is to let the database do the arithmetic in one statement, UPDATE book SET stock = stock - 1, or to lock the row while reading it (SELECT ... FOR UPDATE), so the second clerk waits for the first to finish.
Double booking. Two customers check whether seat 14C is free at the same moment, both see "free," and both book it. Application checks alone can't prevent this, because both checks happen before either insert. A UNIQUE constraint on (flight_id, seat) makes the database reject the second insert, whatever the timing.
Databases offer several isolation levels, trading safety for concurrency. Read Committed, the default in many systems, prevents reading uncommitted data. Serializable, the strictest, makes concurrent transactions behave as if they ran one at a time, at the cost of more waiting or retries.
The design lesson: express invariants as constraints where possible, because constraints are checked atomically by the database and can't be raced. Rules that live only in application code are much harder to protect under concurrency.
Step 8 of 13Practice · Code challenge · SQL
A legacy order_flat table repeats each customer's email on every order, and an update anomaly has crept in. Return the customer_id of every customer who appears with more than one different email.
The database for this exercise (tables and rows)
CREATE TABLE order_flat (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
customer_email TEXT,
total REAL
);
INSERT INTO order_flat VALUES
(1, 7, 'ana@example.com', 30.0),
(2, 7, 'ana@example.com', 12.5),
(3, 8, 'ben@example.com', 44.0),
(4, 7, 'ana.silva@example.com', 18.0),
(5, 9, 'chen@example.com', 9.0),
(6, 8, 'ben@example.com', 21.0);- Result matches the expected table
Step 9 of 13Practice · What would you do?
What would you do?
A concert ticket site checks in application code whether a seat is free before inserting a booking. During a busy sale, some seats get sold twice. What is the most robust fix?
Step 10 of 13Tap to reveal
A design review checklist
Every table describes one thing
Can you state in one sentence what a row represents? "One row per book per order" is clear; "a customer, or sometimes an order" is a red flag.
Keys are sound
Each table has a primary key that is unique, not null and stable. Natural candidate keys are declared UNIQUE even when a surrogate key is used.
Relationships are explicit
Every relationship has a foreign key, with NOT NULL where participation is mandatory and a deliberate ON DELETE action.
Normalized to 3NF
No multivalued cells or repeating groups, no partial or transitive dependencies. Any denormalization is documented with its reason and sync method.
Types and constraints fit the data
Exact decimals for money, real date types for dates, CHECKs for ranges and allowed values, and as few nullable columns as the business allows.
Indexes match the queries
Foreign keys and frequent filters are indexed, composite indexes have the right column order, and there are no unused indexes on write-heavy tables.
Names are clear and consistent
One naming style, no reserved words, no cryptic abbreviations, and foreign keys named after what they reference.
Step 11 of 13Learn
Common design smells
Experienced reviewers recognize problem patterns at a glance. A few of the most common:
- Comma-separated lists in a column (tags = 'sale,new,featured'). Always a hidden many-to-many relationship that needs its own table.
- Numbered columns (phone1, phone2, phone3; q1_sales ... q4_sales). A repeating group that caps the data and complicates queries.
- The "one true lookup table": a single codes table holding countries, statuses, currencies and genres together, distinguished by a type column. It prevents proper foreign keys and type checks for each kind of code.
- Entity-attribute-value tables: a generic table of (entity_id, attribute_name, value) rows used instead of real columns. It feels flexible, but every value becomes text, constraints become impossible and simple queries turn into tangles of self-joins.
- Storing derived data without a plan: an age column that never gets updated, or an order total that drifts from its lines.
- Missing foreign keys "for performance." The integrity they provide is almost always worth far more than the small cost, and orphaned rows are expensive to clean up later.
Each smell is a shortcut that saves minutes during design and costs weeks later. When you see one, ask what real-world structure it is hiding, and model that structure directly.
Step 12 of 13Practice · Select all that apply
A schema review finds these columns and tables. Which are design smells that should be fixed? Select all that apply.
Select all that apply.
Step 13 of 13Practice · Choose one
Two cashiers sell the same book at the same moment. Each application reads stock = 5, subtracts 1 in code and writes back 4. Which change prevents the lost update most simply?
Lesson complete!