Sub topic 3
Updating from another table with UPDATE ... FROM
This chapter assumes you can write SELECT queries with WHERE and INNER JOIN, and that you know single-table UPDATE. It also assumes you know primary and foreign keys and can run statements in psql or another PostgreSQL client.
Why PostgreSQL has no UPDATE ... JOIN
MySQL and SQL Server let you write UPDATE a JOIN b ON .... PostgreSQL does not. It has an extra clause, FROM, that you add to UPDATE. The tables you list there can be used in the WHERE clause and in the expressions of SET.
The general form is:
UPDATE target_table [AS alias]
SET column = expression [, ...]
FROM other_table [AS alias] [, ...]
WHERE join_condition [AND other_filters];The target table is the table being modified. It is named right after UPDATE, and it is never repeated in the FROM list unless you deliberately want a self-join. The FROM tables only supply values and filters. PostgreSQL never changes them.
A worked example
Suppose a table products holds current prices. A staging table price_updates holds new prices that arrived from a supplier. This setup creates both tables with a few rows:
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2) NOT NULL
);
CREATE TABLE price_updates (
product_id integer NOT NULL REFERENCES products (id),
new_price numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO products (id, name, price) VALUES
(1, 'Notebook', 4.00),
(2, 'Pen', 1.50),
(3, 'Stapler', 9.00);
INSERT INTO price_updates (product_id, new_price) VALUES
(1, 4.50),
(2, 1.75);Now copy each new price into products:
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;psql answers UPDATE 2. The count is the number of target rows changed. Check the result:
SELECT id, name, price FROM products ORDER BY id;The stapler still costs 9.00. It has no row in price_updates, so it never joined and was left alone. Products 1 and 2 now carry 4.50 and 1.75.
How PostgreSQL evaluates the statement
Conceptually, PostgreSQL joins the target table to the FROM tables using the WHERE condition. For each target row that has a joined partner, it evaluates the SET expressions with the partner's values available, then writes the new row version. The planner may pick a hash join, merge join, or nested loop, just as it would for a SELECT. This is why an index on the join column matters for large updates, a topic a later chapter covers.
Two consequences follow from this model:
- The join is an inner join. A target row with no match in the
FROMtables is skipped, not set to NULL. - Each target row is updated at most once. If several
FROMrows match one target row, PostgreSQL still performs only one update and uses one of the matches. Which one it picks is not defined. A later chapter on multiple matches shows how to control this.
Filtering with columns from the joined table
The WHERE clause can combine the join condition with any other filters. Those filters can test columns from either table. The next example cancels open orders that belong to closed customers. Here is the setup:
CREATE TABLE customers (
id integer PRIMARY KEY,
name text NOT NULL,
status text NOT NULL DEFAULT 'active'
);
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers (id),
total numeric(10,2) NOT NULL,
status text NOT NULL DEFAULT 'open'
);
INSERT INTO customers (id, name, status) VALUES
(1, 'Ada', 'active'),
(2, 'Bruno', 'closed');
INSERT INTO orders (id, customer_id, total, status) VALUES
(10, 1, 25.00, 'open'),
(11, 2, 40.00, 'open'),
(12, 2, 15.00, 'shipped');The update below uses the customer's status to choose which orders change. Nothing from customers is copied into SET:
UPDATE orders AS o
SET status = 'cancelled'
FROM customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
AND o.status = 'open';Only order 11 changes. Order 10 belongs to an active customer, and order 12 is already shipped. This shows that a joined table can serve only as a filter. You do not have to read a value from it.
Setting several columns and computing values
SET accepts several assignments, and each right-hand side can be an expression that mixes both tables. This version applies the new price and skips rows whose price would not change:
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id
AND p.price IS DISTINCT FROM u.new_price;The last condition has a practical purpose. PostgreSQL writes a whole new row version for every updated row, even when the new value equals the old one. Skipping unchanged rows reduces table bloat and write-ahead log volume. IS DISTINCT FROM is used instead of <> because it treats NULL as an ordinary value to compare. With <>, a comparison involving NULL yields NULL and the row would be skipped.
You can also list more than one table in FROM, either separated by commas or with explicit JOIN ... ON syntax. The target table still cannot appear on the left of a JOIN inside FROM. You link it to the other tables through WHERE.
What goes on the left of SET
The left side of each assignment is a bare column name of the target table. You cannot qualify it with the alias:
-- Fails with a syntax error
UPDATE products AS p
SET p.price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;Write SET price = ... instead. On the right side, qualify columns freely. Qualification is required whenever a name exists in both tables. For example, if both products and price_updates had a column named created_at, then created_at on its own would raise column reference "created_at" is ambiguous. Habitually qualifying every column in a statement with a join avoids that error and makes the statement easier to review.
Common errors at a glance
| Symptom | Likely cause |
|---|---|
| `syntax error at or near "."` in SET | The column on the left of `=` was qualified with an alias. |
| `column reference "id" is ambiguous` | An unqualified column name exists in both the target and a `FROM` table. |
| `UPDATE 0` | The join condition matched nothing, or a filter excluded every row. |
| Unexpected row count or wrong values | The join condition is missing or incomplete, or several rows match each target row. The next chapters cover both. |
| `table name "products" specified more than once` | The target table was repeated in `FROM` without a different alias. |
Looking ahead
UPDATE ... FROM is the PostgreSQL way to set values from another table. When the FROM source may hold several rows per target row, or when you need unmatched rows to be handled differently, a subquery in SET can be a better fit. Both topics get their own chapters. The same FROM approach applies to deletes through DELETE ... USING.
Exercise
The table price_updates has rows for products 1 and 2 only. You run: UPDATE products AS p SET price = u.newprice FROM priceupdates AS u WHERE u.productid = p.id; What happens to product 3, and what row count does psql report if the products table has three rows? Then fix this statement so it also compiles: UPDATE products AS p SET p.price = u.newprice FROM priceupdates AS u WHERE u.productid = p.id;
Show answer
Product 3 has no matching row in priceupdates, so the inner join excludes it and its price is unchanged. psql reports UPDATE 2. The second statement fails because the column on the left side of SET cannot be qualified with the alias. Change it to SET price = u.newprice.