Sub topic 2
When the rows to change depend on another table
This chapter assumes you can write SELECT with WHERE and INNER JOIN. It also assumes you know single-table UPDATE and DELETE, and that you understand primary and foreign keys. You can run every statement in psql or any other PostgreSQL client.
The limit of a single-table statement
A plain UPDATE or DELETE names one table. Its WHERE clause can only use that table's columns. This works as long as the facts that decide which rows to change are stored in the same row.
Often they are not. Typical requests look like this:
- "Cancel all open orders that belong to closed customers." The order status is in
orders, but the customer status is incustomers. - "Set each product's price to the value in the price-change list." The new value is in
price_updates, not inproducts. - "Delete orders whose customer no longer exists." The deciding fact is the absence of a row in another table.
In each case the target table is the table you change. The other table only supplies information. The rest of this tutorial is about how to bring that information into the statement.
The schema used in this tutorial
The examples in this chapter and the following ones use four tables. A price_updates table is a staging table: it holds price changes waiting to be applied.
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'
);
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()
);Load a few rows so you can check each result:
INSERT INTO customers (id, name, status) VALUES
(1, 'Ada', 'active'),
(2, 'Ben', 'closed'),
(3, 'Cy', 'closed');
INSERT INTO orders (id, customer_id, total, status) VALUES
(101, 1, 40.00, 'open'),
(102, 2, 25.00, 'open'),
(103, 2, 80.00, 'shipped'),
(104, 3, 15.00, 'open');
INSERT INTO products (id, name, price) VALUES
(1, 'Pen', 2.00),
(2, 'Notebook', 5.00),
(3, 'Stapler', 9.00);
INSERT INTO price_updates (product_id, new_price) VALUES
(1, 2.50),
(2, 5.75);Ben (2) and Cy (3) are closed. Ben has an open order (102) and a shipped one (103). Cy has one open order (104). Ada's order (101) must not change. The Stapler has no pending price change.
Why a single-table WHERE fails
Try to write the cancellation as if orders could see customers:
UPDATE orders
SET status = 'cancelled'
WHERE status = 'open'
AND customers.status = 'closed';PostgreSQL rejects it:
ERROR: missing FROM-clause entry for table "customers"The statement's scope contains only orders. A table must be brought into scope before its columns can be used. In a SELECT you do that with FROM ... JOIN. An UPDATE or DELETE needs an equivalent.
What other databases do, and what PostgreSQL does
Some databases let you write a join directly after the target table:
-- MySQL style. This is NOT valid PostgreSQL.
UPDATE orders
JOIN customers ON customers.id = orders.customer_id
SET orders.status = 'cancelled'
WHERE customers.status = 'closed';PostgreSQL has no UPDATE ... JOIN and no DELETE ... JOIN. It reports ERROR: syntax error at or near "JOIN". Instead it has two clauses that add extra tables to the statement:
UPDATE ... FROMfor updates.DELETE ... USINGfor deletes.
Both clauses list the extra tables. You write the join condition yourself in the WHERE clause. Chapters 3 and 4 cover the exact syntax. For now, keep the model: the statement has one target table and zero or more source tables.
The model: one target, several sources
When you join in an UPDATE or DELETE, you choose the rows to change by building a joined set of rows, the same way a SELECT does. Then PostgreSQL applies the change to the target table's side of each joined row.
Three consequences follow from this model.
- Only the target table changes. The source tables are read, never written. Cancelling Ben's orders leaves the
customerstable untouched. - Each target row is changed at most once. If the join produces several source rows for one target row, PostgreSQL does not apply the update several times. It picks one source row. Chapter 7 covers this, because the pick is arbitrary.
- A target row that matches nothing is skipped. With an inner-join style condition, unmatched rows are neither updated nor deleted.
A preview you can always run first
Because the selection is just a join, you can write it as a SELECT first. This shows which rows would be affected:
SELECT o.id, o.customer_id, o.status, c.status AS customer_status
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE c.status = 'closed'
AND o.status = 'open';With the sample data it returns orders 102 and 104. Order 103 is excluded because it is shipped, and order 101 because Ada is active. If this SELECT returns the right rows, you have the logic for the modification. The next chapters convert it into UPDATE ... FROM and DELETE ... USING. This habit is the base of the safe workflow in chapter 11.
You can sometimes avoid the join clause
Not every cross-table change needs FROM or USING. A subquery in the WHERE clause can bring in the deciding fact:
UPDATE orders
SET status = 'cancelled'
WHERE status = 'open'
AND customer_id IN (
SELECT id FROM customers WHERE status = 'closed'
);This cancels orders 102 and 104. It works well when the other table only decides which rows to change. It becomes awkward when you also need to copy a value from the other table. A subquery in SET must return exactly one value per target row, and it needs extra care:
UPDATE products
SET price = (
SELECT u.new_price
FROM price_updates AS u
WHERE u.product_id = products.id
);With the sample data this fails:
ERROR: null value in column "price" of relation "products" violates not-null constraintThe Stapler has no row in price_updates. The subquery returns no row, which becomes NULL, and price forbids NULL. Without that constraint the statement would have silently erased the Stapler's price. Notice also that this statement touched every product, not just the matched ones. A join-based statement avoids this by design, because unmatched target rows never enter the joined set.
Chapter 8 compares these subquery forms with FROM and USING in detail.
Choosing the approach
| Situation | Typical tool | Why |
|---|---|---|
| Other table only decides which rows change | `IN` or `EXISTS` subquery, or `FROM`/`USING` | The condition needs no value copied into the row |
| Other table supplies a new value | `UPDATE ... FROM` | One join gives access to several source columns at once |
| Rows to delete depend on matching rows elsewhere | `DELETE ... USING` | The join condition sits in `WHERE`, close to the filters |
| Rows to delete have no match elsewhere | `NOT EXISTS` | Joins only produce matched rows (chapter 9) |
None of these is always best. Pick the one whose meaning is easiest to read, and check it with a SELECT first.
Summary
- A single-table
UPDATEorDELETEcannot see columns from other tables. Referencing them givesmissing FROM-clause entry. - PostgreSQL has no
UPDATE ... JOINorDELETE ... JOIN. It usesUPDATE ... FROMandDELETE ... USING. - A join-based modification has one target table, which changes, and source tables, which are only read.
- A target row is changed at most once, and unmatched target rows are skipped.
- You can always rehearse the selection as a
SELECT ... JOINfirst.
Exercise
Using the sample data, which orders does the following statement cancel, and why does it leave order 103 alone? UPDATE orders SET status = 'cancelled' WHERE status = 'open' AND customer_id IN (SELECT id FROM customers WHERE status = 'closed');
Show answer
It cancels orders 102 and 104. Their customers (Ben and Cy) are closed and the orders are open. Order 103 belongs to a closed customer, but its status is 'shipped', so the status = 'open' condition excludes it. Order 101 belongs to an active customer.
Exercise
Write a SELECT with a join that previews which products have a pending price change, showing the product name, its current price, and the new price. How many rows should it return with the sample data, and which product is missing?
Show answer
SELECT p.name, p.price, u.newprice FROM products AS p JOIN priceupdates AS u ON u.productid = p.id; It returns two rows (Pen and Notebook). The Stapler is missing because it has no row in priceupdates, so the inner join drops it. That is the same reason a join-based UPDATE would leave the Stapler unchanged.