Learning navigation

Code with Animation

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.

SQL5 min readConcept 30 of 44

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.

UPDATE members
SET email = 'ben@new.test'
WHERE id = 2;
members (3 rows, next id: 4)
idintegernametextemailtext
1Ashaasha@mail.test
2Benben@mail.test
3ChenNULL

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.

  1. 1`UPDATE members SET name = 'X'` is run with no WHERE on a table of 3 rows. What happens?
  2. 2`DELETE FROM members WHERE id = 99` matches no row. What does it do?
  3. 3An UPDATE would change rows 2 and 3, but row 2 would break a UNIQUE rule. What is the result?

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.