Sub topic 6
Changing Rows with `UPDATE`
Assume you already know basic SELECT queries, tables, rows, columns, and WHERE clauses. This chapter uses the orders table:
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
total NUMERIC(10, 2) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new'
);
INSERT INTO orders (id, customer_id, total, status)
VALUES
(100, 1, 49.99, 'new'),
(101, 2, 75.00, 'new'),
(102, 1, 20.00, 'cancelled');The working model
UPDATE changes existing rows. The statement has three important parts:
UPDATE table_name
SET column_name = new_value
WHERE condition;The database first finds rows matching the WHERE condition. It then calculates each new value and writes the changes. If you omit WHERE, every row is updated.
Updating selected rows
To ship one order, identify it with its primary key:
UPDATE orders
SET status = 'shipped'
WHERE id = 100;The WHERE clause is the safety boundary. A condition that matches no rows changes nothing. A condition that matches many rows changes all of them.
You can preview the target rows before changing them:
SELECT id, status
FROM orders
WHERE status = 'new';
UPDATE orders
SET status = 'processing'
WHERE status = 'new';The SELECT and UPDATE use the same condition. Check the returned rows and their count before running the update, especially when the condition is based on text or dates.
Expressions and multiple columns
The right side of SET can use the current value of a column. This update increases every new order by 10 percent and changes its status:
UPDATE orders
SET total = total * 1.10,
status = 'repriced'
WHERE status = 'new';Each assignment uses the row’s values as they existed when the statement began. Separate assignments with commas, not AND.
A NULL value needs special care. Comparisons such as column = NULL do not match missing values. Use IS NULL or IS NOT NULL:
UPDATE orders
SET status = 'needs-review'
WHERE status IS NULL;Common errors and safer habits
| Problem | Safer habit |
|---|---|
| Updating every row accidentally | Preview with `SELECT` and keep a precise `WHERE` |
| Matching the wrong rows | Use a primary key or another unique condition |
| Replacing a value instead of computing it | Use an expression such as `total * 1.10` |
| Treating `NULL` like ordinary text | Use `IS NULL` or `IS NOT NULL` |
For important changes, run the update in a transaction. You can inspect the result and use ROLLBACK if it is wrong:
BEGIN;
UPDATE orders
SET status = 'cancelled'
WHERE id = 101;
SELECT id, status
FROM orders
WHERE id = 101;
ROLLBACK;Use COMMIT instead of ROLLBACK when the result is correct.
Exercise
Write an UPDATE statement that changes order 102 to status 'refunded' only when its current status is 'cancelled'.
Show answer
UPDATE orders SET status = 'refunded' WHERE id = 102 AND status = 'cancelled';