Tables and data
SQL, how to update data
Learn how to update data in a SQL table with the UPDATE command, and why the WHERE clause matters so you do not accidentally change every row.
8 minute lesson
Use UPDATE to change existing rows. Target a stable key when you intend to change one record:
UPDATE people
SET age = 8
WHERE id = 2;
The database evaluates the WHERE condition for every candidate row. Only rows where it is true are changed.
Preview the same condition first:
SELECT id, name, age
FROM people
WHERE id = 2;
After the update, check both the affected-row count reported by your client and the stored result. An affected count of zero can mean the identifier was wrong or another process already changed the row.
Without WHERE, every row is updated:
UPDATE people
SET age = 8;
That syntax is valid when you deliberately want a table-wide change. It is dangerous when one condition was forgotten.
NULL also matters. WHERE email <> 'ada@example.com' does not include rows whose email is NULL, because the comparison is unknown. Add OR email IS NULL when those rows should change too.
For an important update, start a transaction, run the update, inspect the rows, then commit. Roll back when the result is not what you intended.
Your action is to update one row by primary key, verify it, and then write—but do not run—a table-wide version. Point to the exact clause that changes the scope.
Lesson completed