Concept · Modifying data

UPDATE

UPDATE changes the columns listed in SET for the rows that match WHERE. The other columns keep their values.

UPDATE example

Order 102 is pending. The block below changes its status, lets you check it and finally restores the original value:

SQL
BEGIN;

SELECT id, status
FROM orders
WHERE id = 102;

UPDATE orders
SET status = 'shipped'
WHERE id = 102
  AND status = 'pending';

SELECT id, status
FROM orders
WHERE id = 102;

ROLLBACK;

The condition includes both the id and the expected status. If someone else had already processed the order, the condition would no longer match and that row would not be changed. After ROLLBACK, the order is back to pending.

Check the result with small data

Two orders are pending; we only want to confirm the first one.

Self-contained test · SQLite
CREATE TABLE demo_orders (id INTEGER, status TEXT);
INSERT INTO demo_orders VALUES (1,'pending'),(2,'pending');
UPDATE demo_orders SET status = 'shipped' WHERE id = 1;
SELECT id, status FROM demo_orders ORDER BY id;
Check result
idstatus
1shipped
2pending

UPDATE changes the rows that match WHERE. Here order 2 stays pending; without WHERE, both would change.

Check your understanding: Which id shows as shipped after running the query?

Show answer

Id 1. Order 2 keeps its pending status because it does not meet WHERE id = 1.

How UPDATE is used

Safety rule: if you cannot say how many rows will change, do not run the statement yet.

What changes from case to case

The new value can be calculated from the existing one. This query adds five units to the stock of each audio product:

SQL
UPDATE products
SET stock = stock + 5
WHERE category = 'Audio';

Before running it, the matching SELECT should show two rows: Headphones and Speaker. After the change, their stock would be 16 and 5 respectively.

Common mix-ups with UPDATE

Leaving out WHERE by accident

Without WHERE, the statement updates every row. Do not add a token condition: copy exactly the filter you already checked with SELECT.

Trusting the “query executed” message alone

A valid statement can affect no rows at all, or far more than expected. Check the number of rows affected and look at the result before committing.