← Back to PostgreSQL, page 1

postgresql-0019 · Easy fresher

Update rows using values from another table with UPDATE ... FROM.

UPDATE target SET ... FROM other WHERE join_condition updates target rows using matching rows from other tables. Rows without a match are left unchanged. If a target row matches several source rows, only one of them is used, unpredictably, so the source must be unique on the join key.

Full answer

Schema and sample rows:

sql
CREATE TABLE products (sku text PRIMARY KEY, price numeric(10,2));
CREATE TABLE price_updates (sku text, new_price numeric(10,2));
INSERT INTO products VALUES ('PEN', 10), ('INK', 45), ('PAD', 60);
INSERT INTO price_updates VALUES ('PEN', 12), ('PAD', 55), ('XYZ', 99);
sql
UPDATE products p SET price = u.new_price FROM price_updates u WHERE u.sku = p.sku RETURNING p.sku, p.price;

Result on PostgreSQL 17:

text
 sku | price
-----+-------
 PEN | 12.00
 PAD | 55.00
(2 rows)
sql
SELECT sku, price FROM products ORDER BY sku;

Result:

text
 sku | price
-----+-------
 INK | 45.00
 PAD | 55.00
 PEN | 12.00
(3 rows)

Two products matched and were updated; INK had no update row and kept its price, and the unknown XYZ had no product to change. RETURNING lists exactly the changed rows, which is a quick sanity check in scripts. Before running such an update, check that price_updates has at most one row per sku (for example with GROUP BY sku HAVING count(*) > 1); otherwise PostgreSQL silently picks one of the duplicates. Running the same join as a SELECT first is a cheap way to preview the change.

sql
CREATE TABLE products (sku text PRIMARY KEY, price numeric(10,2));
CREATE TABLE price_updates (sku text, new_price numeric(10,2));
INSERT INTO products VALUES ('PEN', 10), ('INK', 45), ('PAD', 60);
INSERT INTO price_updates VALUES ('PEN', 12), ('PAD', 55), ('XYZ', 99);

UPDATE products p SET price = u.new_price FROM price_updates u WHERE u.sku = p.sku RETURNING p.sku, p.price;

SELECT sku, price FROM products ORDER BY sku;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • UPDATE ... FROM joins another table
  • Unmatched rows stay unchanged
  • Duplicate source rows give unpredictable results
  • RETURNING shows changed rows
  • Preview with a SELECT

Common mistakes

  • Repeating the target table in FROM, creating a self-join
  • Updating from a source with duplicate keys

Follow-ups

  • How would you write this with MERGE?
  • How do you update from a CSV file?

Tips

  • Warn about duplicate source rows