Recipe · SQL recipes

UPDATE with JOIN: updating one table from another

UPDATE with JOIN updates the rows of one table using values from a related table. The syntax depends on the database (UPDATE … FROM, UPDATE … JOIN or MERGE), and the source must provide a single match per row.

Before continuing: This entry is part of the UPDATE guide. If you are new to the topic, start with UPDATE.

Query

Updating from a source with unique keys
UPDATE products
SET price = (
  SELECT n.price
  FROM new_prices AS n
  WHERE n.product_id = products.id
)
WHERE EXISTS (
  SELECT 1 FROM new_prices AS n
  WHERE n.product_id = products.id
);

The helper table new_prices must have a unique product_id. Check the selection with SELECT and rehearse the update in a transaction. WHERE EXISTS leaves the price of unmatched products untouched.

Cases that change the result

First turn the UPDATE into a SELECT

Before changing data, run the same relationship as a read query. That lets you check the scope, any duplicates and the new values without changing a single row.

Safe preview
SELECT p.id, p.name, p.price AS current_price,
       n.price AS new_price
FROM products AS p
JOIN new_prices AS n
  ON n.product_id = p.id
ORDER BY p.id;

If this SELECT returns two rows for the same p.id, stop. PostgreSQL warns that a UPDATE ... FROM should produce at most one joined row per target row; SQLite also documents that if there are several matches, one of them may be picked arbitrarily.

Three checks before changing data

  1. One match per target row: protect new_prices.product_id with a key or constraint UNIQUE if the model requires a single row per product.
  2. Preflight: compare the current rows with the new values using SELECT.
  3. Transaction: if the engine and environment allow it, run the change inside a transaction and query again before COMMIT.

A JOIN that multiplies the target row

Do not treat a one-to-many join as if it were one-to-one. If you need to derive a single value from many rows, group first or define an unambiguous rule.

Key differences between engines

PostgreSQL

PostgreSQL
UPDATE products AS p
SET price = n.price
FROM new_prices AS n
WHERE p.id = n.product_id;

The target table is not repeated in FROM unless you are doing a self join.

SQLite 3.33+

SQLite added UPDATE FROM in version 3.33.0, aiming for compatibility with the PostgreSQL form.

SQLite
UPDATE products AS p
SET price = n.price
FROM new_prices AS n
WHERE p.id = n.product_id;

MySQL

MySQL
UPDATE products AS p
JOIN new_prices AS n
  ON n.product_id = p.id
SET p.price = n.price;

MySQL supports a multi-table update syntax. That variant does not use FROM after SET.

SQL Server

SQL Server
UPDATE p
SET p.price = n.price
FROM products AS p
JOIN new_prices AS n
  ON n.product_id = p.id;

In Transact-SQL, the target table also appears inside the FROM.