Databases & SQL Master Course — 060. Safe Write Workflow Lab
Lesson 060 Safe Write Workflow Lab
Prerequisites and objectives
Combine lessons 051–059 into a rehearsed change workflow. You will define a change set, preview its targets, apply guarded updates inside a transaction, verify both changed and protected rows, and record a recovery decision. This lab corrects two fictional draft label prices without touching a published label.
Create the practice fixture
Run the setup in a fresh disposable SQLite database. All amounts are integer cents in one fictional currency. The correction plan records the approved identifiers, expected revisions, and intended replacement prices. It is a teaching fixture, not evidence of approval to change any real catalog.
CREATE TABLE labels (
label_id INTEGER PRIMARY KEY,
status TEXT NOT NULL,
price_cents INTEGER NOT NULL CHECK(price_cents>=0),
revision INTEGER NOT NULL
);
INSERT INTO labels VALUES
(1,'Draft',500,2),(2,'Draft',700,3),(3,'Published',900,1);
CREATE TABLE correction_plan (
label_id INTEGER PRIMARY KEY,
expected_revision INTEGER NOT NULL,
new_price_cents INTEGER NOT NULL
);
INSERT INTO correction_plan VALUES (1,2,550),(2,3,750);
Write the acceptance contract first
The intended change is exact: label one moves from 500 to 550 cents and revision two to three; label two moves from 700 to 750 and revision three to four. Label three stays Published at 900 cents and revision one. Two targets must match their expected draft state. A missing or stale target should stop the whole correction.
Separate evidence from assumptions. The plan tells us what was intended, while a current preview tells us what presently exists. A count of two is insufficient if the two identifiers are wrong. A total price increase of one hundred cents is also insufficient if a published row was changed by mistake.
SELECT p.label_id,l.status,l.price_cents,l.revision,
p.expected_revision,p.new_price_cents
FROM correction_plan AS p
LEFT JOIN labels AS l ON l.label_id=p.label_id
ORDER BY p.label_id;

Rehearse the guarded mutation
The update requires a plan row with the same identifier and current revision, as well as Draft status. The assignment reads the new price from that unique plan row. The plan’s primary key prevents several proposed prices for one label. Revision increments make the accepted transition visible and help a repeated run fail its old-state guard.
BEGIN;
UPDATE labels
SET price_cents=(SELECT p.new_price_cents FROM correction_plan AS p
WHERE p.label_id=labels.label_id),
revision=revision+1
WHERE status='Draft'
AND EXISTS (SELECT 1 FROM correction_plan AS p
WHERE p.label_id=labels.label_id
AND p.expected_revision=labels.revision);
SELECT * FROM labels ORDER BY label_id;
SELECT SUM(price_cents) FROM labels;
ROLLBACK;
SELECT SUM(price_cents) FROM labels;
The statement affects two rows. The full ordered result verifies each replacement and the untouched published row. The total rises from 2100 to 2200 cents, matching the additional control calculation. Finally, rollback proves that this rehearsal can restore its starting state. Neither the table preview nor a reassuring total replaces checking the actual identifiers and values.
Plan the failure path before execution
Run precondition checks and writes within the intended transaction boundary, and inspect the actual affected count. A successful statement can still match fewer rows than expected. If only one planned row qualifies, the application should rollback this all-or-nothing correction rather than accept a partial result. SQLite SQL alone does not interpret a printed count as an instruction to branch.
A real change record would identify the authorized scope, environment, backup or recovery method, expected outcomes, and who decides whether to commit. This course performs only disposable rehearsals. A rollback protects uncommitted database work; it is not a substitute for a tested recovery plan after commit or for controlling external notifications.
Four worked exercises
Exercise 1
List planned labels whose current state fails the precondition. Expect none in the clean fixture.
Worked solution
SELECT p.label_id FROM correction_plan AS p LEFT JOIN labels AS l ON l.label_id=p.label_id WHERE l.label_id IS NULL OR l.status<>'Draft' OR l.revision<>p.expected_revision ORDER BY p.label_id;
The empty result means both planned rows currently exist, remain Draft, and match the expected revisions. This is useful evidence, not permanent permission: later changes can invalidate a preview, which is why the mutation repeats the guards.
Exercise 2
Simulate a stale revision for label two and show why an affected-row check matters.
Worked solution
BEGIN;
UPDATE labels SET revision=4 WHERE label_id=2;
UPDATE labels
SET price_cents=(SELECT p.new_price_cents FROM correction_plan AS p
WHERE p.label_id=labels.label_id),
revision=revision+1
WHERE status='Draft'
AND EXISTS (SELECT 1 FROM correction_plan AS p
WHERE p.label_id=labels.label_id
AND p.expected_revision=labels.revision);
SELECT * FROM labels ORDER BY label_id;
ROLLBACK;
Only label one qualifies. The statement succeeds, but the business contract expected two corrections. The correct lab response is rollback. The simulated concurrent state is also undone because it was created inside this isolated rehearsal transaction.
Exercise 3
Apply the correction twice within one rehearsal and inspect the second affected count.
Worked solution
BEGIN;
UPDATE labels
SET price_cents=(SELECT p.new_price_cents FROM correction_plan AS p
WHERE p.label_id=labels.label_id),
revision=revision+1
WHERE status='Draft'
AND EXISTS (SELECT 1 FROM correction_plan AS p
WHERE p.label_id=labels.label_id
AND p.expected_revision=labels.revision);
UPDATE labels
SET price_cents=(SELECT p.new_price_cents FROM correction_plan AS p
WHERE p.label_id=labels.label_id),
revision=revision+1
WHERE status='Draft'
AND EXISTS (SELECT 1 FROM correction_plan AS p
WHERE p.label_id=labels.label_id
AND p.expected_revision=labels.revision);
SELECT label_id,revision FROM labels ORDER BY label_id;
ROLLBACK;
The second run matches zero rows because both revisions advanced beyond the plan’s expected values. This guards against blindly replaying the old plan. A caller should distinguish an already-applied plan from a genuinely stale or inconsistent state.
Exercise 4
Verify the protected published label and the plan itself after the mutation.
Worked solution
BEGIN;
UPDATE labels
SET price_cents=(SELECT p.new_price_cents FROM correction_plan AS p
WHERE p.label_id=labels.label_id),
revision=revision+1
WHERE status='Draft'
AND EXISTS (SELECT 1 FROM correction_plan AS p
WHERE p.label_id=labels.label_id
AND p.expected_revision=labels.revision);
SELECT * FROM labels WHERE label_id=3;
SELECT * FROM correction_plan ORDER BY label_id;
ROLLBACK;
The published row and plan remain unchanged. Testing protected rows adds evidence that the predicate did not exceed its scope. Preserve the original plan rather than quietly rewriting expected revisions merely to make a failed retry pass.
Knowledge check
Question 1
What is the required affected count for the clean plan?
- Two
- One because UPDATE is one statement
- Three because the table has three rows
- Zero because every rehearsal rolls back
Answer and explanation
A. Two distinct planned labels meet the guards; rollback happens after the count is inspected.
Question 2
Why repeat expected revision in the mutation?
- It sorts the RETURNING output
- It makes the earlier preview remain valid indefinitely
- It makes every retry affect two rows
- The current row may no longer match the preview
Answer and explanation
D. The predicate protects the expected state at the actual write, not just at an earlier preview.
Question 3
If only one target qualifies, what satisfies this lab contract?
- Commit because no SQL error occurred
- Rollback the partial correction
- Increase the expected count afterward
- Remove Draft filtering and rerun blindly
Answer and explanation
B. The requested operation is all-or-nothing across both targets.
Question 4
Why check label three?
- To add it automatically to the plan
- To prove all database tables are unchanged
- To verify a protected row stayed unchanged
- To determine the affected count from the total row count
Answer and explanation
C. Negative scope checks catch unintended effects on rows outside the change set.
Question 5
What does the price total prove by itself?
- Only the aggregate total, not exact row correctness
- Every intended identifier changed correctly
- No published row could have changed
- The transaction has already committed
Answer and explanation
A. Different incorrect row changes can produce the same total.
Pitfalls and summary
Do not improvise a wider predicate when the planned one matches fewer rows. Stop, preserve the evidence, and resolve the mismatch. A safe workflow joins a precise change contract, guarded writes, positive and negative verification, a deliberate transaction ending, and recovery notes. This lab ends in rollback, with all source rows restored.
SQLite behavior and references
Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.
Primary references
- SQLite transactions: Transaction boundaries and error handling
- SQLite conflict handling: Statement failure versus transaction rollback
- SQLite UPSERT: Uniqueness conflict targets and conditional updates