skipnothing/SQL
UNIT 07

Writes, Constraints & Transactions

INSERT, UPDATE, DELETE, constraints, ACID, isolation levels, locks

Reading data is half the story. Writing it means the database has to protect what's already there: constraints enforce shape, transactions group writes into all-or-nothing units, isolation defines what concurrent writers see.

Loading…
BUILDS ON
TOPICS
#24

INSERT, UPDATE, DELETE

Append rows with INSERT (omitted columns fall to default or NULL), rewrite matched rows with UPDATE, remove matched rows with DELETE, and read the affected-row count, then watch a missing WHERE turn one row into the whole table.

A new order lands in the orders table, and correcting the amount on row id = 104 leaves the other three alone. Forget to name the row, and every order changes, with only one number to warn you.

12 min
#25

Constraints

Declare NOT NULL, UNIQUE, CHECK, and foreign-key constraints so the table rejects a bad write itself, then choose an ON DELETE action (CASCADE, SET NULL, RESTRICT) and predict which write each one blocks.

An order arrives carrying amount = -5, and a plain orders table stores it without complaint. Add one rule to that column and the same write bounces back rejected, the bad row never lands.

14 min
#26

Transactions & ACID

Wrap two writes in BEGIN/COMMIT/ROLLBACK so a crash can't strand a transfer half-done, trace the bank-transfer all-or-nothing, then map each of ACID's four guarantees to the failure it stops and see where consistency stops at the rules you actually declared.

An accounts table holds $300 across two rows. Move $100 from one to the other as a debit then a credit, let the machine die between them, and $100 is simply gone: one row charged, the other never paid.

15 min
#27

Isolation Levels & Locks

Set an isolation level per transaction to trade concurrency for protection from dirty reads, non-repeatable reads, and phantoms, lock a row with SELECT FOR UPDATE so a concurrent writer waits, and break a deadlock by retrying the transaction the engine aborts.

Two clerks open the accounts table at once. One reads a balance of 100, the other commits a change to 120, and the first reads that same row again, now seeing a number that wasn't there when its transaction began.

15 min
All units