Before continuing: This entry is part of the UPDATE guide. If you are new to the topic, start with UPDATE.
Query
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.
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
- One match per target row: protect
new_prices.product_idwith a key or constraintUNIQUEif the model requires a single row per product. - Preflight: compare the current rows with the new values using SELECT.
- 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
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.
UPDATE products AS p
SET price = n.price
FROM new_prices AS n
WHERE p.id = n.product_id;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
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.