Sub topic 6
Changing rows with UPDATE
UPDATE changes values in rows that already exist. This chapter covers the statement's structure, how the WHERE clause chooses rows, how NULL and defaults behave in SET, and what happens when a change breaks a constraint.
It assumes you can write SELECT ... WHERE queries, know the common column types, and understand primary and foreign keys at a basic level. It also assumes you have created the customers and orders tables from the earlier chapter.
The shape of an UPDATE
An UPDATE has three parts: the table to change, the new values (SET), and the rows to change (WHERE).
UPDATE table_name
SET column1 = value1,
column2 = value2
WHERE condition;To follow the examples, start from this data. Skip any rows you already inserted in earlier chapters, because a repeated primary key is rejected.
INSERT INTO customers (id, name, email)
VALUES
(1, 'Ada Lovelace', '[email protected]'),
(2, 'Grace Hopper', '[email protected]'),
(3, 'Alan Turing', NULL);
INSERT INTO orders (id, customer_id, total)
VALUES
(100, 1, 40.00),
(101, 1, 15.50),
(102, 2, 99.99);Now mark one order as shipped:
UPDATE orders
SET status = 'shipped'
WHERE id = 100;The database does the following:
- It finds every row where the
WHEREcondition is true. - It builds the new version of each of those rows.
- It checks the new rows against the table's constraints.
- It stores the new rows and reports how many it changed.
The WHERE clause decides the scope
WHERE in an UPDATE works like WHERE in a SELECT. Any row for which the condition is true is changed. Rows where it is false or unknown are left alone.
If you leave out WHERE, the condition is effectively "every row":
-- Do not run this: it sets every order's status to 'shipped'.
UPDATE orders
SET status = 'shipped';Most clients run this without a warning. Some tools have a "safe updates" mode that blocks it, but the SQL language does not. A later chapter covers previewing the affected rows with SELECT. For now, write the WHERE clause before you write the SET clause.
Matching by key or by condition
An update that filters on the primary key changes at most one row. A filter on any other column can match many rows, or none:
UPDATE orders
SET status = 'priority'
WHERE total > 50;Zero matching rows is not an error
If no row matches, the statement succeeds and reports 0 rows affected. A typo in the key therefore does not produce an error:
UPDATE orders
SET status = 'shipped'
WHERE id = 1000; -- no such order: succeeds, 0 rows affectedCheck the row count your client reports. In application code, treat an unexpected 0 as a failure, for example when you meant to update exactly one row.
NULL in the WHERE clause
NULL is never equal to anything, including another NULL. email = NULL evaluates to unknown, so no row matches. Use IS NULL:
UPDATE customers
SET status = 'review'
WHERE email IS NULL; -- changes Alan Turing's rowSetting several columns
List the columns in one SET, separated by commas. All the changes happen together in one row version:
UPDATE customers
SET name = 'Ada King',
email = '[email protected]'
WHERE id = 1;Each column appears at most once in the SET list. Naming a column twice is an error in most databases.
Setting NULL and defaults
A column can be set to NULL if it allows it:
UPDATE customers
SET email = NULL
WHERE id = 3;On a NOT NULL column the same statement fails. customers.name is NOT NULL, so SET name = NULL is rejected.
To restore a column's default value, use the DEFAULT keyword:
UPDATE customers
SET status = DEFAULT
WHERE id = 3;PostgreSQL, MySQL, and SQL Server accept this. SQLite does not support DEFAULT in an UPDATE, so write the literal value there (SET status = 'active').
The default is applied only to columns you name. An UPDATE never touches the columns missing from SET. This is different from INSERT, where an omitted column receives its default.
All new values come from the old row
The right-hand side of each assignment reads the row as it was before the statement. In standard SQL, this swaps two values:
UPDATE orders
SET total = customer_id,
customer_id = total
WHERE id = 102;This example is only illustrative, because it would put a decimal total into the key column. The point is that standard SQL evaluates every right-hand side against the original row.
The next chapter covers expressions like total * 1.10 in more detail.
Counting what changed
Databases report affected rows in different ways:
| Database | How you see the count |
|---|---|
| PostgreSQL | `UPDATE 3` command tag in `psql` |
| MySQL | "Rows matched" and "Changed"; rows set to their existing value are not counted as changed by default |
| SQL Server | "(3 rows affected)", or the `@@ROWCOUNT` variable |
| SQLite | The `changes()` function, or the driver's row count |
The MySQL distinction matters. An UPDATE that sets a column to the value it already holds matches the row but changes nothing. Compare "matched" with "changed" when you debug an update that seems to do nothing.
When the new row is rejected
The database checks constraints on the new version of each row. If any row violates one, the whole statement fails and none of the rows are changed. The statement is all-or-nothing, even when you updated 1,000 rows and only one is bad.
Three typical failures:
-- Foreign key: customer 999 does not exist.
UPDATE orders
SET customer_id = 999
WHERE id = 100;
-- UNIQUE: Ada's new email is already taken.
UPDATE customers
SET email = '[email protected]'
WHERE id = 2;
-- NOT NULL: name may not be NULL.
UPDATE customers
SET name = NULL
WHERE id = 2;The first fails with a foreign key error. The second fails with a unique violation, because customer 1 now holds that email. The third fails with a not-null violation. The error messages differ by database, but each names the constraint. Read the constraint name first, then check the new value you tried to store.
A bulk update can fail on a unique column in a way that looks wrong. This statement shifts every id up by one:
UPDATE customers
SET id = id + 1;In PostgreSQL the unique check can fail partway through, because row 1 becomes 2 while the old row 2 still exists. Whether it succeeds depends on the database and on how the constraint is defined. Changing primary keys is also risky because other tables reference them. Treat keys as values you do not update.
Common mistakes
- Forgetting
WHERE. Every row changes. This is the most expensive mistake. - Using
= NULL. The condition never matches, so 0 rows change and you get no error. - Putting a
WHEREcondition on the wrong column. An update withWHERE name = 'Ada'silently matches nothing if the stored name is'Ada Lovelace'. - Ignoring the row count. A successful statement is not proof that the intended rows changed.
- Updating a column twice in
SET. Most databases reject it. Merge the two assignments. - Assuming the update is permanent. Depending on your client's autocommit setting, it may still be open inside a transaction. The transactions chapter covers this.
Exercises
Exercise
Order 101 should be marked 'shipped'. A colleague runs UPDATE orders SET status = 'shipped' WHERE id = 1010; and the database reports success. What happened, and how would you have noticed?
Show answer
No order has id 1010, so the condition matched zero rows. An UPDATE that matches nothing is not an error, so the statement succeeded and changed no data. You would notice by reading the row count, which was 0 instead of 1.
Exercise
A table has 500 rows. You run an UPDATE that sets a UNIQUE email column for all of them, and row 312 gets a value that already exists. How many rows end up changed, and why?
Show answer
None. The UPDATE is atomic: if any new row version violates a constraint, the statement fails as a whole and the table stays as it was before.
Exercise
Write an UPDATE that sets the status of every customer with no email address to 'review'. Why does WHERE email = NULL not work?
Show answer
UPDATE customers SET status = 'review' WHERE email IS NULL; The comparison email = NULL evaluates to unknown, never true, so no row matches. NULL has to be tested with IS NULL.