SQL · Module 3 · Lesson 21 min read

UPDATE: Changing Data Safely

Syntax

SQL
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;

⚠️ The golden rule: always use WHERE

Without WHERE, every row is updated. Safe habits:

  1. Write the SELECT with your WHERE first, and check which rows it returns
  2. Change SELECT … into UPDATE … SET …, keeping the same WHERE
  3. Run it inside BEGIN; … and check the row count before COMMIT
  4. Use RETURNING * to see exactly what changed

Expressions in SET

  • Based on the current value: SET balance = balance - 500
  • Functions: SET title = initcap(title)
  • CASE for conditional updates: SET priority = CASE WHEN amount > 5000 THEN 'high' ELSE 'normal' END
  • Set to NULL: SET note = NULL
  • Back to the default: SET tags = DEFAULT

Updating using another table (UPDATE … FROM)

ini
UPDATE expenses e
SET note = 'Big spender'
FROM users u
WHERE u.id = e.user_id AND u.monthly_budget > 35000;

The row count

PostgreSQL reports UPDATE n — the number of rows changed. If it's not what you expected, ROLLBACK.

updated_at columns

Many tables keep an updated_at timestamp. Set it in the UPDATE (SET …, updated_at = now()) or automatically with a trigger (Unit 13).

Example

SQL
-- Step 1: preview the rows
SELECT id, title, amount FROM expenses WHERE title = 'Fuel';

-- Step 2: update in a transaction and check the result
BEGIN;
UPDATE expenses
SET amount = amount * 1.10,                       -- fuel price went up 10%
    note   = 'Price adjusted'
WHERE title = 'Fuel'
RETURNING id, title, amount;                      -- 2 rows: 3300.00, 3520.00
COMMIT;

-- Conditional update with CASE: tag big expenses
UPDATE expenses
SET tags = CASE
             WHEN amount >= 5000 THEN array_append(tags, 'big')
             ELSE tags
           END
WHERE spent_on >= '2026-11-01';

SELECT title, amount, tags FROM expenses WHERE 'big' = ANY(tags);

-- Update using another table: mark bills paid for users in Kathmandu
UPDATE bills b
SET paid = true
FROM users u
WHERE u.id = b.user_id AND u.city = 'Kathmandu'
RETURNING b.title, u.name;

-- ❌ The classic accident (don't run!):
-- UPDATE users SET monthly_budget = 0;   -- every user's budget is now 0

-- Safety net: if the count looks wrong, roll back
BEGIN;
UPDATE users SET city = 'Unknown' WHERE city IS NULL;   -- UPDATE 1
ROLLBACK;