Sub topic 13
Updating and deleting based on other tables
This chapter assumes you can write a SELECT with JOIN and WHERE, and that you know the customers and orders tables from the start of this tutorial. It also assumes you know about foreign keys and transactions.
Often the rows you want to change are identified by data in a different table. You might put every order from an inactive customer on hold, or delete orders that belong to customers with a certain email domain. The WHERE clause of UPDATE and DELETE can only test columns of the target table directly, so you need a way to reach the other table.
Two families of solutions
- Subqueries. A subquery inside
WHEREorSETworks in every major dialect. This is the portable choice. - Joins in the statement itself.
UPDATE ... FROM,UPDATE ... JOIN,DELETE ... USINGand similar forms are often easier to read, but the syntax is not standard and differs between databases.
The portable approach: subqueries
Suppose you want to put on hold every order that belongs to an inactive customer. IN with a subquery expresses this directly.
UPDATE orders
SET status = 'on_hold'
WHERE customer_id IN (
SELECT id FROM customers WHERE status = 'inactive'
);EXISTS with a correlated subquery does the same thing. The subquery refers to the outer table (orders.customer_id), so it is evaluated against each candidate row.
UPDATE orders
SET status = 'on_hold'
WHERE EXISTS (
SELECT 1
FROM customers
WHERE customers.id = orders.customer_id
AND customers.status = 'inactive'
);Both forms also work with DELETE. Delete child rows before parent rows so the foreign key is not violated.
DELETE FROM orders
WHERE customer_id IN (
SELECT id FROM customers WHERE status = 'inactive'
);A deletion that depends on a missing match is a common case. This removes inactive customers who have no orders, and it works in every dialect:
DELETE FROM customers
WHERE status = 'inactive'
AND NOT EXISTS (
SELECT 1 FROM orders WHERE orders.customer_id = customers.id
);Copying a value from another table
Subqueries can also supply the new value. A scalar subquery (one that returns a single value) can appear on the right side of SET. Here each order for an inactive customer gets a status that records why it is held:
UPDATE orders
SET status = (
SELECT 'held_' || customers.status
FROM customers
WHERE customers.id = orders.customer_id
)
WHERE EXISTS (
SELECT 1
FROM customers
WHERE customers.id = orders.customer_id
AND customers.status = 'inactive'
);The || string concatenation operator works in PostgreSQL and SQLite. MySQL uses CONCAT() by default, and SQL Server uses + or CONCAT().
The WHERE EXISTS part is not decoration. A scalar subquery that finds no row returns NULL, so without the filter every order without a match would get NULL in status. Here that would fail because of NOT NULL, but on a nullable column it would silently erase data. If the subquery finds more than one row, the statement fails with an error.
Join forms by dialect
The join forms let you read columns from both tables in SET and WHERE without repeating a subquery for each column. Every example below does the same thing as the IN example above.
UPDATE
PostgreSQL and SQLite (3.33 or later) put the other table in a FROM clause and join it in WHERE:
UPDATE orders
SET status = 'on_hold'
FROM customers
WHERE orders.customer_id = customers.id
AND customers.status = 'inactive';SQL Server also uses FROM, but the target is usually named by alias, and the join is written explicitly:
UPDATE o
SET o.status = 'on_hold'
FROM orders AS o
INNER JOIN customers AS c ON c.id = o.customer_id
WHERE c.status = 'inactive';MySQL puts the join right after UPDATE and places SET after it:
UPDATE orders AS o
JOIN customers AS c ON c.id = o.customer_id
SET o.status = 'on_hold'
WHERE c.status = 'inactive';DELETE
PostgreSQL uses USING to list the extra tables:
DELETE FROM orders
USING customers
WHERE orders.customer_id = customers.id
AND customers.status = 'inactive';SQL Server and MySQL name the table to delete from between DELETE and FROM, and then join:
DELETE o
FROM orders AS o
INNER JOIN customers AS c ON c.id = o.customer_id
WHERE c.status = 'inactive';SQLite has no join form for DELETE, so use the subquery version.
| Dialect | UPDATE with another table | DELETE with another table |
|---|---|---|
| PostgreSQL | `UPDATE ... SET ... FROM ... WHERE` | `DELETE FROM ... USING ... WHERE` |
| SQL Server | `UPDATE alias SET ... FROM ... JOIN ...` | `DELETE alias FROM ... JOIN ...` |
| MySQL | `UPDATE ... JOIN ... SET ...` | `DELETE alias FROM ... JOIN ...` |
| SQLite | `UPDATE ... SET ... FROM ...` (3.33+) | subquery only |
| Standard SQL | subquery | subquery |
Gotchas
A missing join condition touches too many rows
In the FROM forms, the link between the tables is just a condition in WHERE. If you forget orders.customer_id = customers.id, every order is paired with every inactive customer. With the constant SET shown above, the result is that every order is updated whenever at least one inactive customer exists.
Do not repeat the target table in PostgreSQL's FROM
In PostgreSQL, writing UPDATE orders ... FROM orders JOIN customers ... adds a second, independent copy of orders. That creates a self-join that is not linked to the rows being updated. List only the other tables in FROM. SQL Server behaves differently: there the FROM clause must repeat the target table (under its alias), as shown above.
Several matches for one row
When the other side of the join has multiple rows for one target row, and the new value comes from that side, the result is ambiguous. For example, setting each customer's status from their orders:
UPDATE customers
SET status = orders.status
FROM orders
WHERE orders.customer_id = customers.id;A customer with five orders matches five rows. PostgreSQL and SQL Server apply only one of them, and which one is not defined. MySQL has the same ambiguity. To make the result predictable, aggregate first (for example, MAX(created_at) in a subquery) or reduce the join to one row per target row.
MySQL and subqueries on the same table
MySQL rejects an UPDATE or DELETE whose subquery reads from the table being changed (error 1093). Wrap the subquery in a derived table, for example WHERE id IN (SELECT id FROM (SELECT id FROM orders WHERE ...) AS t), or use the join form.
A safe workflow
- Write the join as a
SELECTand read the rows. - Count them and compare with what you expect.
- Change
SELECTtoUPDATEorDELETE, keeping the sameFROMandWHERElogic. - Run it inside a transaction, check the result, then
COMMITorROLLBACK.
SELECT o.id, o.status, c.email
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE c.status = 'inactive';Exercise
You run this PostgreSQL statement to delete orders belonging to inactive customers, and it deletes every order in the table. Why, and how do you fix it? DELETE FROM orders USING customers WHERE customers.status = 'inactive';
Show answer
The WHERE clause has no condition linking orders to customers, so each order is paired with every inactive customer. As long as one inactive customer exists, every order qualifies for deletion. Add the join condition: DELETE FROM orders USING customers WHERE orders.customer_id = customers.id AND customers.status = 'inactive'; Preview with the equivalent SELECT first.
Exercise
Write a statement that works in every dialect and deletes customers whose status is 'inactive' only if they have no orders. Why is NOT EXISTS safer than NOT IN here?
Show answer
DELETE FROM customers WHERE status = 'inactive' AND NOT EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = customers.id); NOT IN returns no matches if the subquery produces any NULL. NOT EXISTS is not affected by NULLs in the subquery.