LLearnCode
Academy/sql/State under change

intermediate · 22 minute study

Make a change an all-or-nothing unit

An order without its lines is not half a successful feature. It is a broken state that later screens, reports and retries must somehow interpret.

Loading progressEvidence grows with practice
Useful preparation · 1 prerequisite

Use this as a map, not a lock. If these ideas are familiar, continue.

First, build a mental model

A transaction creates a private draft of a set of changes. COMMIT makes the accepted unit durable; ROLLBACK discards the unit.

  1. Group changes according to the invariant they must preserve together. A server function making several unrelated HTTP calls is not automatically one database transaction.
  2. A successful first statement does not mean the workflow succeeded. Capture errors and explicitly finish with COMMIT or ROLLBACK.
  3. PostgreSQL and SQLite differ after some statement errors: PostgreSQL normally leaves an explicit transaction aborted until rollback; SQLite can leave it active with earlier statements pending.
  4. A transaction is not an idempotency key. Repeating an already committed transaction can still create a second business effect.
Read the codesql · educational example
BEGIN;
INSERT INTO orders(id, customer_id, company_id, status, total_cents)
VALUES (104, 1, 'company-a', 'draft', 2500);
INSERT INTO order_lines(order_id, product_id, quantity, unit_cents)
VALUES (104, 1, 1, 2500);
ROLLBACK;
SELECT id FROM orders WHERE id = 104;
  1. Begin

    The inserted order and its line belong to one transaction.

  2. Rollback

    Both inserts are discarded even though each individual statement was valid.

  3. Readback

    On a reset fixture, order 104 is absent. Replacing ROLLBACK with COMMIT preserves both records.

Production thinking

Take this beyond the example.

Prove the failure path: inject a failure after the first effect, inspect every related table, and verify nothing from the failed unit escaped. Then test replay of a completed request separately.

Sources and further reading

Your evidence

unseen is a local learning signal, not a credential or proof of production competence.

Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.

Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.

Next lesson · Reason about two writers, not one happy path →