Updating and Deleting Data (Carefully!)
Changing what's already there
Data does not stay the same forever. A user changes their email, a shop marks an order as shipped, a moderator removes a spam comment. SQL gives you two statements for this: UPDATE to change existing rows, and DELETE to remove them.
UPDATE
UPDATE users SET email = 'new@example.com' WHERE id = 5;Read this as: "in the users table, set the email column to this new value, but only for the row where id equals 5." The WHERE clause here works exactly like it does in SELECT, it decides which rows get touched.
DELETE
DELETE FROM comments WHERE id = 42;This removes the one row where id equals 42 from the comments table, and nothing else.
Now the important warning
Look closely at both examples above: they both include a WHERE clause. This is not optional caution, it is essential. If you leave WHERE out of an UPDATE, every single row in the table gets updated. If you leave WHERE out of a DELETE, every single row in the table gets deleted. There is usually no undo button.
UPDATE users SET status = 'banned';
-- DANGER: with no WHERE clause, this bans every user in the tableA safety habit worth building now
Before you run an UPDATE or DELETE, especially on a table that matters, run a SELECT first using the exact same WHERE condition. This lets you see precisely which rows would be affected, with zero risk, before you commit to changing or removing anything.
SELECT * FROM comments WHERE id = 42;
-- Check this looks right, then run the DELETE with the same WHEREThis one habit, checking with SELECT first, will save you from more accidents than almost anything else in this entire course.
Quick check
Q1 What happens if you run UPDATE users SET status = 'banned'; with no WHERE clause?
Q2 Before running a DELETE with a WHERE clause you are not fully sure about, what is a smart safety step?
Want to save your progress? It's free.
Create a free account