Sub topic 3
Updating from Another Table with `UPDATE ... FROM`
Assume you know basic SELECT, WHERE, and INNER JOIN syntax, single-table UPDATE statements, table aliases, and primary and foreign keys. This chapter uses PostgreSQL tables named products and price_updates.
PostgreSQL does not use an UPDATE ... JOIN clause. Instead, UPDATE ... FROM lets one table provide values or filtering conditions for an update to another table.
The basic pattern
The table named immediately after UPDATE is the target table. PostgreSQL changes rows in that table. Tables listed after FROM provide related data.
UPDATE target AS t
SET column_name = source.value
FROM source_table AS source
WHERE source.key = t.key;The join condition belongs in WHERE. It connects each target row to the source row that supplies the new value.
For example, suppose price_updates contains new prices for products:
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;This statement does the following:
- Reads a product row from
products. - Finds rows in
price_updateswhoseproduct_idequals that product'sid. - Sets the product's
pricetonew_price.
The products table is still the only table being modified.
| Part | Purpose |
|---|---|
| `UPDATE products AS p` | Chooses the rows to change |
| `SET price = u.new_price` | Defines the new value |
| `FROM price_updates AS u` | Adds source rows |
| `WHERE u.product_id = p.id` | Matches source rows to products |
Filtering with the related table
The source table can also determine which target rows qualify. This example changes only open orders belonging to closed customers:
UPDATE orders AS o
SET status = 'cancelled'
FROM customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
AND o.status = 'open';The first condition is the relationship between the tables. The other conditions restrict the update. Without o.status = 'open', already cancelled or completed orders could also be overwritten.
Important safety rule
A missing join condition can create a Cartesian product, which pairs every product with every update row:
-- Dangerous
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u;This statement has no relationship between p and u. Every product can match every staging row. The final value may be unpredictable, and many rows may receive incorrect prices.
For example:
SELECT p.id, p.price AS old_price, u.new_price
FROM products AS p
JOIN price_updates AS u
ON u.product_id = p.id;If this preview returns the intended products and values, the corresponding update is easier to trust.
Exercise
Which table does PostgreSQL modify in UPDATE products AS p SET price = u.new_price FROM price_updates AS u WHERE u.product_id = p.id?
Show answer
PostgreSQL modifies products. The price_updates table supplies matching values but is not changed.