Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 11 / Topic 2 of 7

UPDATE: conditional, computed, joined

UPDATE ... SET ... WHERE you know in essence; three refinements make it professional.

Computed from the old value — ingredient costs rose, Kitchen prices go up 10%:

UPDATE products
SET price = round(price * 1.10, 2)
WHERE category_id = 6
RETURNING name, price;
     name     | price  
--------------+--------
 Chef Knife   |  88.00
 Coffee Maker | 132.00
(2 rows)

UPDATE 2

Read the row count, always. UPDATE 2 when you expected 2 is confirmation; UPDATE 7 when you expected 2 is an alarm that fired before the damage spread.

UPDATE ... FROM joins other tables into the decision. Suppose everything from UK suppliers needs a flag:

ALTER TABLE products ADD COLUMN import_note text;
UPDATE products AS p
SET import_note = 'imported: ' || s.country
FROM suppliers AS s
WHERE s.supplier_id = p.supplier_id
  AND s.country <> 'India'
RETURNING p.name, p.import_note;
ALTER TABLE
        name        |    import_note    
--------------------+-------------------
 SQL for Beginners  | imported: UK
 Postgres Deep Dive | imported: UK
 Chef Knife         | imported: Germany
 Coffee Maker       | imported: Germany
(4 rows)

UPDATE 4

The FROM brings suppliers into scope exactly like a join; the WHERE is both join condition and filter. And the first habit from your Stage 1 days still rules: pre-flight the WHERE as a SELECT before any UPDATE you can't afford to get wrong — same condition, zero risk, five seconds.

🧪 Quick quiz — answer from memory, then check.

  1. What does SET price = price * 1.1 see on the right-hand side?
  2. What is UPDATE ... FROM for?
Show the answers
  1. The old value of the row being updated — computed updates are the norm.
  2. Letting the update's SET/WHERE use columns from other tables — a join folded into the write.

Exercise 2: Book prices up 5%, with the receipt

What to do: Both habits on display: pre-flight the WHERE as a SELECT, then raise Books (category 2) by 5% in one statement that reports the new prices itself.

Sample output:

        name        | price 
--------------------+-------
 SQL for Beginners  | 36.75
 Postgres Deep Dive | 57.75
(2 rows)

UPDATE 2

💡 Hint: round(price * 1.05, 2) and RETURNING. The tag said 2 — expected 2. Done.


Show the solution to Exercise 2
-- Exercise 2: Book prices up 5%, with the receipt
-- Pre-flight first — same WHERE, zero risk:
SELECT name, price FROM products WHERE category_id = 2;
-- Then the write, returning exactly what changed:
UPDATE products
SET price = round(price * 1.05, 2)
WHERE category_id = 2
RETURNING name, price;

Search the guide