Sub topic 6
The missing join condition and other common mistakes
This chapter assumes you can write UPDATE ... FROM and DELETE ... USING statements, and that you know INNER JOIN semantics. Every example uses the customers, orders, products, and price_updates tables from earlier in the tutorial.
PostgreSQL does not stop you from writing a join that matches too much. The statement is valid, it runs, and it reports a row count. The damage shows up later. This chapter covers the mistakes that cause this and how to spot each one.
How the join drives the change
UPDATE ... FROM first builds a set of joined rows. It then changes each target row that appears in that set. The join condition, normally written in WHERE, decides which target rows pair with which source rows. If the condition is missing or too loose, the set contains pairings you never intended.
Mistake 1: the missing join condition
This statement has a FROM clause but no condition linking the two tables.
-- Dangerous: no join condition, so every product is joined to every staging row
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u;Without a condition, the join is a Cartesian product: every product pairs with every row in price_updates. Each product is still updated only once. PostgreSQL picks one of its paired rows, and which one is not predictable. The command tag says UPDATE n, where n is the number of products, so the output looks normal. Every product now has a price taken from an arbitrary staging row.
One edge case is easy to miss. If price_updates is empty, the Cartesian product is empty too, and nothing is updated. A statement can look correct in a test with an empty staging table and only misbehave in production.
The same mistake in a delete is worse.
-- Dangerous: deletes EVERY order if at least one closed customer exists
DELETE FROM orders AS o
USING customers AS c
WHERE c.status = 'closed';The WHERE clause filters the customers, but it never mentions o. Every order pairs with every closed customer, so every order is deleted.
The fix is to state how the tables relate.
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed';Mistake 2: `OR` breaking the join condition
The join condition can be present and still stop applying to some rows. AND binds more tightly than OR, so an unparenthesized OR splits the condition into two independent halves.
-- Dangerous: parsed as (join AND closed) OR open
UPDATE orders AS o
SET status = 'cancelled'
FROM customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
OR o.status = 'open';Any open order satisfies the second half without any link to a customer. It pairs with every customer row, so every open order is cancelled, including those of active customers. If you need OR, wrap it in parentheses and keep the join condition outside.
UPDATE orders AS o
SET status = 'cancelled'
FROM customers AS c
WHERE o.customer_id = c.id
AND (c.status = 'closed' OR c.status = 'suspended')
AND o.status = 'open';Mistake 3: repeating the target table in `FROM`
If you write the target table in FROM under a new alias, PostgreSQL treats it as a second, separate copy. The result is a self-join, not a reference to the row being updated.
-- Wrong: p2 is a different copy of products, not the target row
UPDATE products AS p
SET price = u.new_price
FROM products AS p2, price_updates AS u
WHERE u.product_id = p2.id;Nothing connects p to p2, so this is another Cartesian product. Every row of p is paired with the matching p2 row. The fix is to list only the source tables in FROM, as in the correct version below.
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;Repeat the target table in FROM only when you want a self-join, such as the deduplication pattern in a later chapter. In that case, the condition between the two copies is required.
Mistake 4: qualifying the column in `SET`
In SET, the left side must be a bare column name of the target table, even when the table has an alias.
-- 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;PostgreSQL reads p.price as a column named p with a subfield price. Write SET price = ... instead. This mistake is annoying but safe: the statement fails, and nothing changes. The right side of SET can still use qualified names such as u.new_price.
Mistake 5: ambiguous column names
If both tables have a column named id or status, an unqualified reference fails.
-- 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';Both orders and customers have a status column. Qualify every column in the WHERE clause and on the right side of SET. The left side of SET is the exception, as in Mistake 4. A related silent failure occurs when you qualify a column with the wrong alias. o.status = 'closed' is valid SQL, but it tests the order's status, not the customer's. It will probably match nothing, and the statement will report UPDATE 0.
Mistake 6: assuming unmatched rows are handled
The FROM form behaves like an inner join. A target row with no match in the source never enters the joined set, so it is not touched. This is usually what you want. It differs from a correlated subquery in SET, which sets unmatched rows to NULL unless you add an EXISTS filter. A later chapter covers that case.
Two details matter here.
NULLjoin keys never match.u.product_id = p.idis never true when either side isNULL. Rows with aNULLkey are silently skipped.- Type and format mismatches are silent skips. If keys are text with different casing or trailing spaces, those rows do not match. The statement succeeds and updates fewer rows than expected.
Summary of symptoms
| Mistake | Typical symptom | Fix |
|---|---|---|
| No join condition | Row count equals the whole target table | Add `target.key = source.key` |
| `OR` outside parentheses | Rows with no relation to the source are changed | Parenthesize the `OR` group |
| Target repeated in `FROM` | Cartesian product or wrong values | List only the source tables |
| `p.price` in `SET` | Error: column "p" does not exist | Use `SET price = ...` |
| Unqualified shared column | Error: ambiguous column | Qualify with aliases |
| `NULL` or mismatched keys | Fewer rows changed than expected | Check key types, case, and `NULL`s |
Catching mistakes before they commit
Two habits catch most of these problems. First, read the command tag. UPDATE 4812 when you expected about 20 is a warning sign. Second, turn the statement into a SELECT using the same FROM and WHERE, and count the target rows it returns.
SELECT count(*) AS affected_orders
FROM orders AS o
JOIN customers AS c ON o.customer_id = c.id
WHERE c.status = 'closed'
AND o.status = 'open';Compare this count with the row count of the real statement, and with the total number of rows in the target table. If the two counts match what you expect and are much smaller than the table, the join is probably right. A later chapter covers the full preview workflow with transactions and RETURNING.
Exercise
This statement is meant to cancel open orders for customers whose status is 'closed'. It reports UPDATE 9500, and the orders table has 9500 rows. What is wrong, and how do you fix it?
UPDATE orders AS o
SET status = 'cancelled'
FROM customers AS c
WHERE c.status = 'closed';
Show answer
There is no condition joining o to c, so every order pairs with every closed customer, and every order is cancelled. The o.status = 'open' filter is also missing. Fix it with WHERE o.customer_id = c.id AND c.status = 'closed' AND o.status = 'open'.
Exercise
Why does UPDATE products AS p SET p.price = u.new_price FROM price_updates AS u WHERE u.product_id = p.id; fail, and does it change any data?
Show answer
In SET, the left side must be a bare column name, so p.price is rejected with an error that column "p" does not exist. The statement fails before running, so no data changes. Write SET price = u.new_price.
Exercise
A statement ends with WHERE o.customer_id = c.id AND c.status = 'closed' OR o.status = 'open'. Which rows does it change beyond the intended ones, and what is the fix?
Show answer
Because AND binds more tightly than OR, the condition means (join AND closed) OR open. Every open order matches the second part and pairs with every customer, so all open orders are changed. Fix it by removing the OR or parenthesizing it, for example WHERE o.customer_id = c.id AND c.status = 'closed' AND o.status = 'open'.