Sub topic 5
Aliases and what you can reference in SET
This chapter assumes you can read the UPDATE ... FROM and DELETE ... USING statements from the previous chapters. It covers three things: how aliases work in those statements, which names are visible in each clause, and what SET can and cannot reference. Most of the errors you hit when writing join-based modifications come from these rules.
The examples use the customers, orders, products, and price_updates tables from earlier in the tutorial.
Aliasing the target table
You can give the target table an alias with AS. The alias is optional but worth using whenever a second table is involved.
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;Once you alias the target, the original table name is hidden for the rest of the statement. This fails:
-- ERROR: invalid reference to FROM-clause entry for table "products"
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = products.id;PostgreSQL's error hint says Perhaps you meant to reference the table alias "p". Choose one name and use it everywhere. The same rule applies to DELETE FROM orders AS o USING customers AS c: after that, write o.customer_id, not orders.customer_id.
Which names each clause can see
The target table and the FROM (or USING) tables are all in scope in the WHERE clause. Some other clauses have narrower rules.
| Clause | Target table columns | FROM / USING table columns |
|---|---|---|
| Left side of `SET` | Bare column names only | Not allowed |
| Right side of `SET` | Yes, as old values | Yes |
| `WHERE` | Yes, as old values | Yes |
| `RETURNING` | Yes, as new values (for `UPDATE`) | Yes |
| `JOIN ... ON` inside `FROM` | No | Yes, for items to its left |
The left side of SET takes a bare column name
The column being assigned always belongs to the target table, so PostgreSQL does not let you qualify it. Writing SET p.price = ... is a syntax error. Write SET price = ....
-- ERROR: column "p" of relation "products" does not exist
UPDATE products AS p
SET p.price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;This also means you cannot update a column of the FROM table. A single UPDATE changes exactly one table. To change two tables, run two statements, or chain them with a data-modifying CTE (covered later in the tutorial).
The right side of SET is an ordinary expression. It can use columns from the target, columns from the FROM tables, functions, and subqueries.
UPDATE products AS p
SET price = round(greatest(u.new_price, p.price * 0.5), 2)
FROM price_updates AS u
WHERE u.product_id = p.id;Here p.price on the right is the value the row has before the statement changes it.
Ambiguous column names
customers and orders both have id and status columns. An unqualified reference to either name in the WHERE clause or on the right of SET is ambiguous, and PostgreSQL rejects it.
-- ERROR: column reference "status" is ambiguous
UPDATE orders AS o
SET status = 'cancelled'
FROM customers AS c
WHERE o.customer_id = c.id
AND status = 'closed';Qualify every column in the WHERE and RETURNING clauses and on the right of SET. Only the left side of SET is exempt, because it can only mean the target table:
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';In this statement, SET status is the order's status. c.status is the customer's status, and o.status is the order's status again. The two meanings of status never collide because each one is qualified, except on the left of SET, where qualification is not allowed.
All SET expressions see the old row
Every expression in the SET list is evaluated against the row as it was before the statement. Assignments do not see each other's results. That makes a swap work without a temporary column:
CREATE TABLE swap_demo (a integer, b integer);
INSERT INTO swap_demo VALUES (1, 2);
UPDATE swap_demo SET a = b, b = a;
SELECT a, b FROM swap_demo; -- a = 2, b = 1The same rule applies when the right side references FROM tables. You never need to worry about the order of the assignments.
You can also assign several columns at once with row syntax. The number of columns on the left must match the number of values on the right.
UPDATE products AS p
SET (name, price) = (upper(p.name), u.new_price)
FROM price_updates AS u
WHERE u.product_id = p.id;Do not repeat the target table in FROM
If you list the target table again in FROM, PostgreSQL treats it as a separate, independent table instance. The two are not the same row. This is the cause of a classic bug:
-- Wrong: the FROM copy of products is not joined to the target row
UPDATE products
SET price = price * 1.1
FROM products AS other
WHERE other.name = 'Widget';Every row of products is joined to the Widget row, so every product is updated, not just the widget. Because the join condition never mentions the target row, the statement does the Cartesian-product mistake from the previous chapter.
Repeating the table is only correct when you want a real self-join, and then you must give both instances different aliases and join them explicitly:
UPDATE products AS p
SET price = ref.price
FROM products AS ref
WHERE ref.name = 'Widget'
AND p.name = 'Widget Deluxe';Each instance has its own alias, so p is the row being changed and ref is a read-only reference row.
Joins inside FROM cannot see the target
You may write explicit JOIN syntax inside FROM. The ON conditions in it can only use the tables inside that FROM list. They cannot refer to the target table.
-- ERROR: invalid reference to FROM-clause entry for table "p"
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
JOIN customers AS c ON c.id = p.id
WHERE u.product_id = p.id;Move any condition that involves the target into WHERE. Use JOIN ... ON only to connect the FROM tables to each other.
RETURNING uses the same aliases
RETURNING can use the target alias and any FROM or USING alias. For an UPDATE, target columns show the new values, and columns from other tables show what they contained when joined.
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id
RETURNING p.id, p.name, p.price AS new_price, u.created_at AS update_time;In a DELETE ... USING, RETURNING can include columns from the USING table, such as c.name, which is useful for logging why each row was removed.
Common mistakes with aliases
- Using the table name after aliasing it. Use the alias.
- Qualifying the column on the left of
SET. Use the bare name. - Leaving a shared column such as
statusoridunqualified inWHEREor on the right ofSET. - Naming the target again in
FROMwithout an alias and a join condition. - Putting a condition on the target inside a
JOIN ... ONinFROM.
Exercise
This statement is meant to mark products as discontinued price 0 when a price update row has newprice = 0, but it fails. List every error you can find and give a corrected version. UPDATE products AS p SET p.price = 0 FROM priceupdates AS u WHERE u.productid = products.id AND newprice = 0;
Show answer
There are two errors that PostgreSQL reports. (1) SET p.price qualifies the target column on the left of SET, which is not allowed; write SET price = 0. (2) products.id uses the real table name after the table was aliased as p; write p.id. The bare newprice is not an error here, because only priceupdates has that column, but qualifying it as u.newprice is clearer. Corrected: UPDATE products AS p SET price = 0 FROM priceupdates AS u WHERE u.productid = p.id AND u.newprice = 0;