Sub topic 11
Subqueries in UPDATE and DELETE
This chapter assumes you can write basic SELECT, WHERE, and ORDER BY queries and use aggregates with GROUP BY. It also assumes you can join tables and that you understand NULL and three-valued logic. You should already know scalar subqueries, multi-row subqueries with IN, and correlated subqueries from earlier chapters.
Why subqueries in data-modifying statements
UPDATE and DELETE decide which rows to change with a WHERE clause. Often the rule for choosing rows lives in another table. For example, "remove orders for closed customers" needs data from customers to change orders. A subquery lets you ask that question inside the statement itself, so you do not have to run a SELECT first and paste the ids back in by hand.
The subquery forms you already know carry over:
- A scalar subquery supplies one value, for use in SET or in a comparison.
- A multi-row subquery supplies a list, for use with IN or NOT IN.
- A correlated subquery refers to the row being updated or deleted.
- EXISTS and NOT EXISTS test for related rows.
The examples use these tables:
customers(id, name, status)orders(id, customer_id, total, status)employees(id, name, salary, department_id)departments(id, name)
Subqueries in the WHERE clause of DELETE
The most common pattern is deleting rows based on a list from another table.
DELETE FROM orders
WHERE customer_id IN (
SELECT id FROM customers WHERE status = 'closed'
);The database evaluates the subquery to find the ids of closed customers. It then deletes each order whose customer_id is in that list. The subquery reads customers, and the DELETE changes only orders.
Preview before you delete
A mistake in a DELETE is expensive. Turn the statement into a SELECT first, using the same WHERE clause:
SELECT *
FROM orders
WHERE customer_id IN (
SELECT id FROM customers WHERE status = 'closed'
);Check the rows and the count. Then replace SELECT * with DELETE. Running the real statement inside a transaction lets you verify the affected-row count and roll back if it looks wrong.
BEGIN;
DELETE FROM orders
WHERE customer_id IN (
SELECT id FROM customers WHERE status = 'closed'
);
-- Check the reported row count, then:
ROLLBACK; -- or COMMIT; once you are satisfiedUsing NOT EXISTS to delete orphans
An orphan is a row whose parent no longer exists. Suppose some orders point to customers that were removed. NOT EXISTS finds them safely:
DELETE FROM orders o
WHERE NOT EXISTS (
SELECT 1
FROM customers c
WHERE c.id = o.customer_id
);Some databases do not accept a table alias in DELETE. MySQL, for instance, allows an alias in the single-table form only from version 8.0.16. If your database rejects the alias, write the table name in the correlation instead:
DELETE FROM orders
WHERE NOT EXISTS (
SELECT 1
FROM customers c
WHERE c.id = orders.customer_id
);Prefer NOT EXISTS over NOT IN here. If customers.id could ever be NULL, NOT IN would match no rows, and the cleanup would silently do nothing. A primary key column cannot be NULL, but the habit protects you when the column is not a key.
Subqueries in UPDATE
UPDATE allows subqueries in two places: the WHERE clause, to choose rows, and the SET clause, to compute new values.
Choosing rows with a subquery
UPDATE employees
SET salary = salary * 1.05
WHERE department_id IN (
SELECT id FROM departments WHERE name = 'Support'
);This gives a 5 percent raise to every employee in the Support department.
Computing a value with a scalar subquery in SET
A subquery in SET must be scalar. It must return at most one row and one column. Here every employee below the company average is raised to that average:
UPDATE employees
SET salary = (SELECT AVG(salary) FROM employees)
WHERE salary < (SELECT AVG(salary) FROM employees);Both subqueries read the table being updated. The behavior of that is covered below.
Correlated subqueries in SET
A correlated subquery in SET computes a different value for each row. This statement stores each customer's order count in a summary column:
UPDATE customers
SET order_count = (
SELECT COUNT(*)
FROM orders o
WHERE o.customer_id = customers.id
);The column order_count is not in the earlier table list. Add it to your test table first if you want to run this statement. COUNT(*) returns 0 for a customer with no orders, so every customer gets a number.
Aggregates other than COUNT behave differently. If you replace COUNT(*) with SUM(o.total), a customer with no orders gets NULL, because SUM over zero rows is NULL. Use COALESCE when you want 0:
UPDATE customers
SET order_total = COALESCE(
(SELECT SUM(o.total) FROM orders o WHERE o.customer_id = customers.id),
0
);Rows the subquery does not match
A correlated scalar subquery in SET that finds no row returns NULL. If the statement has no WHERE clause, the column is set to NULL for every unmatched row. This is a frequent source of data loss. Compare these two statements:
-- Risky: customers without a matching row get NULL
UPDATE customers
SET region = (
SELECT r.region
FROM regions r
WHERE r.postal_code = customers.postal_code
);
-- Safer: only update customers that have a match
UPDATE customers
SET region = (
SELECT r.region
FROM regions r
WHERE r.postal_code = customers.postal_code
)
WHERE EXISTS (
SELECT 1
FROM regions r
WHERE r.postal_code = customers.postal_code
);The second form repeats the subquery. That is the cost of staying portable. Some databases offer UPDATE ... FROM (PostgreSQL, SQL Server) or UPDATE ... JOIN (MySQL) to avoid the repetition, but the syntax differs by product.
The subquery must return one row
If a scalar subquery in SET returns more than one row, most databases raise an error. In the example above, two rows in regions with the same postal_code would make the statement fail. PostgreSQL reports "more than one row returned by a subquery used as an expression". MySQL has a similar error. Fix the cause with a unique constraint on postal_code, or narrow the subquery so it returns one row.
Reading the table you are modifying
Because the subquery often reads the same table that the statement changes, the rules about this matter.
- PostgreSQL, SQL Server, and Oracle allow it. The subquery sees the data as it was when the statement started, so rows changed earlier in the same statement do not alter the result.
- MySQL rejects a statement that updates or deletes from a table and selects from the same table in a subquery, with error 1093: "You can't specify target table for update in FROM clause". The usual workaround is to wrap the subquery in a derived table, which forces MySQL to build it first as a temporary result.
-- MySQL: this raises error 1093
DELETE FROM employees
WHERE salary < (SELECT AVG(salary) FROM employees);
-- MySQL: wrapping the subquery in a derived table works
DELETE FROM employees
WHERE salary < (
SELECT avg_salary
FROM (SELECT AVG(salary) AS avg_salary FROM employees) AS t
);The wrapper works because the derived table is materialized before the DELETE starts. In the standard-conforming databases, the same guarantee comes from the statement-level snapshot, so you can write the first form directly.
What the statement sees
Note the "No or unknown" branch. A WHERE condition that evaluates to NULL keeps the row, just as in a SELECT. This is why NOT IN with a NULL in the list deletes nothing.
Choosing between a subquery and a join
Many databases let you write the same change with a join. The syntax is not portable, so the subquery form is often the better default when you want one statement that works across products.
| Situation | Subquery form | Join form |
|---|---|---|
| Filter rows by membership in another table | `WHERE col IN (SELECT ...)` | `DELETE ... USING` or `DELETE ... JOIN` |
| Set a column from another table | Correlated scalar subquery in SET | `UPDATE ... FROM` or `UPDATE ... JOIN` |
| Need several columns from the other table | One subquery per column | One join serves all columns |
| Portability | Works in all major products | Syntax differs by product |
When you set several columns from the same source row, repeated subqueries get long and may run the same lookup several times. Use the product's join form in that case. Row-value syntax such as SET (a, b) = (SELECT x, y ...) also works in PostgreSQL and Oracle, but not in every database.
Safety checklist
- Write the WHERE clause as a SELECT first and inspect the rows.
- Run the change inside a transaction and check the affected-row count.
- In UPDATE ... SET with a correlated subquery, add a WHERE EXISTS so unmatched rows keep their old values.
- Use NOT EXISTS instead of NOT IN unless the subquery column is NOT NULL.
- Make sure scalar subqueries in SET can return only one row.
- Check your database's rule on reading the target table in a subquery.
Exercises
Exercise
A table products(id, name, category_id) and a table categories(id, name, discontinued) are given. Write a DELETE that removes products whose category is marked discontinued (discontinued = TRUE). Then say why you might prefer NOT EXISTS over NOT IN for the opposite task, deleting products whose category row does not exist.
Show answer
DELETE FROM products WHERE category_id IN (SELECT id FROM categories WHERE discontinued = TRUE); For the opposite task, NOT EXISTS is safer because NOT IN returns no rows if the subquery produces even one NULL, so the cleanup would silently delete nothing. NOT EXISTS is not affected by NULL values.
Exercise
This statement sets customers.last_order_total from the latest order. Customers with no orders currently end up with NULL, which overwrites a value they already had. How do you change the statement so those customers keep their old value? The statement is: UPDATE customers SET lastordertotal = (SELECT o.total FROM orders o WHERE o.customer_id = customers.id ORDER BY o.id DESC LIMIT 1);
Show answer
Add a WHERE EXISTS clause that tests for at least one order: UPDATE customers SET lastordertotal = (SELECT o.total FROM orders o WHERE o.customerid = customers.id ORDER BY o.id DESC LIMIT 1) WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customerid = customers.id); Customers without orders no longer match the WHERE clause, so the UPDATE does not touch them. In SQL Server, replace LIMIT 1 with SELECT TOP 1, and in Oracle use FETCH FIRST 1 ROW ONLY.
Exercise
In MySQL, DELETE FROM employees WHERE salary < (SELECT AVG(salary) FROM employees); fails with error 1093. What causes the error, and how do you rewrite the statement?
Show answer
MySQL does not allow a subquery to read the same table that the statement is modifying. Wrap the subquery in a derived table so it is built first: DELETE FROM employees WHERE salary < (SELECT avgsalary FROM (SELECT AVG(salary) AS avgsalary FROM employees) AS t);