Sub topic 1
Updating and Deleting Rows with Joins in PostgreSQL
Prerequisites
This chapter assumes you know basic SELECT, WHERE, and INNER JOIN syntax. You should understand single-table UPDATE and DELETE statements, table aliases, and primary and foreign keys. You should also be able to run statements in psql or another PostgreSQL client.
Recap: single-table UPDATE and DELETE
An UPDATE statement changes column values in the rows that match its WHERE condition. A DELETE statement removes the rows that match its WHERE condition. Both affect only the table named after the keyword.
UPDATE orders
SET status = 'shipped'
WHERE id = 42;
DELETE FROM orders
WHERE status = 'cancelled';Every column in the WHERE clause must belong to the target table. The rest of this chapter covers what to do when it does not.
When the rows to change depend on another table
The rule for choosing rows often lives in a different table. For example, you may want to delete the orders of customers whose status is 'closed'. The status is stored in the customers table, so a plain WHERE clause on orders cannot see it. You need a join.
PostgreSQL has no UPDATE ... JOIN or DELETE ... JOIN syntax. It uses two clauses instead: FROM for UPDATE and USING for DELETE.
Updating from another table with UPDATE ... FROM
The FROM clause lists extra tables. The WHERE clause links those tables to the target table.
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;The SET clause can read columns from the tables listed in FROM. Each product with a matching row in price_updates receives that row's new price.
Deleting based on another table with DELETE ... USING
The USING clause works the same way for DELETE.
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed';Only orders belonging to closed customers are removed.
Exercise
Write a statement that sets orders.status to 'cancelled' for every open order whose customer has status 'closed'.
Show answer
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';