UPDATE & DELETE
Change and remove rows safely: how WHERE decides which rows, what the row count tells you, and why a missing WHERE is dangerous.
Change rows and remove rows
UPDATE table SET column = value WHERE condition changes the rows that match. DELETE FROM table WHERE condition removes the rows that match. Both use the same WHERE you already know.
The new value in SET can use the old value of the row, as in SET price = price * 1.10. You can set several columns at once, separated by commas.
Data changes
People change their email, orders are cancelled, accounts are closed. UPDATE and DELETE are how a database keeps up. They are also the statements that can do the most damage by accident.
One row, then every row
UPDATE members
SET email = 'ben@new.test'
WHERE id = 2;The tag UPDATE 1 says one row changed. Because id is the primary key, WHERE id = 2 addresses exactly one row. Only a primary key lets you target one row reliably.
Leave out the WHERE and every row is changed: UPDATE members SET name = upper(name) shows UPDATE 3. DELETE FROM members with no WHERE deletes every row. The manual's own comment is "Caveat programmer".
A WHERE that matches no rows is not an error. You simply get UPDATE 0 or DELETE 0.
Change a few rows, then a lot
Run the UPDATE with WHERE, then without. Try the UPDATE that matches nothing and the one that breaks UNIQUE. Press Reset table whenever you want a fresh start.
| idinteger | nametext | emailtext |
|---|---|---|
| 1 | Asha | asha@mail.test |
| 2 | Ben | ben@mail.test |
| 3 | Chen | NULL |
Pick a statement and press Run statement. Compare the row count in the tag with the number of rows you meant to change.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- UPDATE ... SET ... WHERE changes matching rows. DELETE FROM ... WHERE removes them.
- With no WHERE, every row is changed or removed, and there is no warning.
- A WHERE that matches no rows is not an error. The tag shows 0.
- A statement is all or nothing. Run the WHERE as a SELECT first, and check the count.
Done with this concept?
Mark it complete to track your progress. No login needed.