Sometimes you need to update rows in one table using values from another table — for example, recalculating a net price based on a discount stored in a separate segment table. PostgreSQL handles this with the UPDATE ... FROM syntax, which joins the target table to one or more additional tables.
UPDATE join syntax
The joined table goes in a FROM clause placed immediately after SET, and the join condition goes in WHERE:
UPDATE table1
SET table1.c1 = new_value
FROM table2
WHERE table1.c2 = table2.c2;
PostgreSQL matches each row in table1 against every row in table2. When the WHERE condition is true, it applies the SET expression using values from both rows.
Practical example: calculating net price from a segment discount
Given a product table and a product_segment table that holds the discount for each segment, calculate and store the net price for every product:
UPDATE product p
SET net_price = price - price * discount
FROM product_segment s
WHERE p.segment_id = s.id;
This joins each product to its segment, reads the discount column, and writes the computed net_price back to the product row — all in a single pass. Table aliases (p and s) keep the statement concise.
After running the update, verify the results:
SELECT id, name, price, net_price, segment_id
FROM product
ORDER BY segment_id, id;
The net_price column now reflects each product's segment-specific discount.
Practical tips
- The
FROMclause performs an implicit inner join — rows in the target table that have no match in the joined table are not updated. - If the joined table can match multiple rows per target row, PostgreSQL picks one match non-deterministically. Ensure the join is one-to-one or add additional filters to make it deterministic.
- Use table aliases to avoid ambiguous column references when both tables share column names.
- Run a
SELECTwith the sameFROMandWHEREconditions first to preview exactly which rows and values will be changed. - You can join more than two tables by adding further comma-separated entries in the
FROMclause.
Reference: PostgreSQL documentation — UPDATE.