Changing rows that already exist
UPDATE rewrites columns on existing rows, DELETE removes rows. Both take the same WHERE clause you know from unit 2, and on both, the WHERE clause is the safety catch:
UPDATE pets SET age = 4 WHERE name = 'Biscuit'; DELETE FROM pets WHERE species = 'cat';
SET lists the changes (SET age = 4, species = 'dog' for several). WHERE decides which rows they hit.
Now the classic disaster: forget the WHERE and the statement applies to every row in the table. UPDATE pets SET age = 99; makes every pet 99. DELETE FROM pets; empties the table. No confirmation, no undo (outside a transaction, unit 10). Every engineer knows a story like this.
Code exercise · sql
Run it. Biscuit's age changes from 3 to 4; nobody else is touched, because the WHERE clause limits the blast radius.
Code exercise · sql
See the disaster safely, in a sandbox. Run it as-is: the UPDATE has no WHERE, so every pet becomes 99 years old.
The professional habit
Before running an UPDATE or DELETE on data you care about, run a SELECT with the exact same WHERE clause first:
SELECT * FROM pets WHERE species = 'cat'; -- looks right? then: DELETE FROM pets WHERE species = 'cat';
The SELECT shows you precisely which rows are about to be affected. If it returns 40,000 rows when you expected 3, you just saved yourself. This costs five seconds and becomes automatic with practice.
Quiz
You mean to give one user a discount but run `UPDATE accounts SET balance = balance + 10;`. What happens?
Code exercise · sql
Your turn. The cafe fired the parrot. Delete Ziggy (and only Ziggy), then rename Mochi to 'Mochi II'. The final SELECT should show exactly two rows.