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.

Use UPDATE to change existing rows. You tell the database which table to touch, which columns to change, and which rows to change them in:

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.

The database tells you how many rows it changed. If you see UPDATE 1, one row matched and was updated. If you see UPDATE 0, the WHERE clause matched nothing, and nothing happened. No error is raised, so check that count.

Update more than one column

You can set several columns in a single statement, separating them with commas:

UPDATE people
SET age = 3, name = 'Roger Jr.'
WHERE id = 2;

Use the current value

The new value does not have to be a fixed one. You can compute it from the current value of the column:

UPDATE people
SET age = age + 1
WHERE name = 'Roger';

This adds one year to everyone named Roger. The same pattern works for strings, numbers, dates, anything the column holds.

Preview before you update

My advice: before running an UPDATE, run a SELECT with the same WHERE clause:

SELECT id, name, age
FROM people
WHERE id = 2;

The rows you get back are the rows the update will touch. If you see more rows than expected, you just saved yourself.

What happens without WHERE?

Here is the classic mistake:

UPDATE people
SET age = 8;

That syntax is valid when you deliberately want a table-wide change. Without a WHERE clause, every row is updated. This is not a syntax error. The database does exactly what you asked. It is one of the most common ways to destroy data, and it takes one missing line.

NULL in WHERE clauses

WHERE email <> '[email protected]' does not include rows whose email is NULL, because the comparison is unknown. Add OR email IS NULL when those rows should change too.

Protect important updates

For an important update, wrap the work in a transaction. Look at the result and roll back if it is wrong:

BEGIN;
UPDATE people SET age = 8 WHERE id = 2;
SELECT * FROM people;
ROLLBACK;

Replace ROLLBACK with COMMIT when the result looks right.

Try this on your own: 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