Video in progress

How do you update rows based on data in another table with `UPDATE ... FROM` and `DELETE ... USING`?

In PostgreSQL, UPDATE t SET ... FROM other WHERE t.x = other.x updates by joining with another table, and DELETE ... USING does the same for deletes. The main trap: if the JOIN gives several matching rows for one target row, the result becomes unpredictable.

📖 Answer

For example, prices are updated from a new price list table:

UPDATE product p
SET    price      = np.price,
       updated_at = now()
FROM   new_prices np
WHERE  np.sku = p.sku
  AND  np.price <> p.price;

Deleting the carts of blocked users:

DELETE FROM cart_items ci
USING  users u
WHERE  u.id = ci.user_id
  AND  u.status = 'BLOCKED';

Key points:

  • If the same sku appears twice in new_prices, PostgreSQL doesn't raise an error; which price gets written is left to chance. Clean the source first with DISTINCT ON or a unique constraint.
  • The np.price <> p.price condition leaves unchanged rows untouched, which means fewer dead tuples and less WAL.
  • This syntax is PostgreSQL-specific. In standard SQL you use a subquery or MERGE (PG15+).

On a big table I run a query like this in chunks rather than all at once, otherwise it holds locks for a long time and produces a lot of WAL.