Sub topic 11
Subqueries in UPDATE and DELETE
This chapter assumes you can write SELECT statements with WHERE, use aggregate functions and GROUP BY, join tables, and reason about NULL and three-valued logic. A subquery in a data-modifying statement helps choose which rows to change or remove.
Use a subquery to choose rows
An UPDATE changes values in rows that match its WHERE condition. A DELETE removes rows that match its WHERE condition. The subquery supplies that condition from another query.
For example, give a 5% raise to employees in departments located in the West:
UPDATE employees
SET salary = salary * 1.05
WHERE department_id IN (
SELECT id
FROM departments
WHERE region = 'West'
);The subquery returns department IDs. The outer UPDATE changes employees whose department_id appears in that result.
The same pattern works with DELETE:
DELETE FROM orders
WHERE customer_id IN (
SELECT id
FROM customers
WHERE status = 'closed'
);The subquery identifies closed customers. The DELETE removes their orders.
A subquery can also return one value. This statement raises employees whose salary is below the company average:
UPDATE employees
SET salary = salary * 1.10
WHERE salary < (
SELECT AVG(salary)
FROM employees
);The scalar subquery must return one value. AVG returns one value, so it is suitable here. A scalar subquery that returns multiple rows causes an error.
Preview before changing data
A safe workflow is to use the same condition in a SELECT first:
SELECT id, customer_id, total
FROM orders
WHERE customer_id IN (
SELECT id
FROM customers
WHERE status = 'closed'
);Check the rows and the count. Then use the condition in the DELETE or UPDATE.
When your database supports transactions, you can also test the change and inspect the result before deciding whether to keep it:
BEGIN;
UPDATE employees
SET salary = salary * 1.05
WHERE department_id IN (
SELECT id
FROM departments
WHERE region = 'West'
);
SELECT id, name, salary
FROM employees
WHERE department_id IN (
SELECT id
FROM departments
WHERE region = 'West'
);
ROLLBACK;Replace ROLLBACK with COMMIT only after verifying the result. Transaction commands and whether a transaction can undo a particular operation depend on the database system.
Prefer EXISTS for related-row tests
Use EXISTS when the question is whether at least one related row exists:
DELETE FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
);This removes customers who have no orders. The subquery is correlated because it refers to c.id from the outer statement. Conceptually, the database tests the subquery for each customer.
NOT EXISTS is often safer than NOT IN. If the subquery used by NOT IN returns a NULL, SQL's three-valued logic can make the condition unknown for every row.
Check the change and the plan
Subqueries in UPDATE and DELETE follow the same filtering rules as subqueries in SELECT. Their greater risk comes from changing or removing data. Use a preview query, a transaction when available, and a precise condition.
For large tables, inspect the query plan for the preview query. Indexes on columns used to connect the outer table and subquery, such as orders.customer_id, can reduce the work. The optimizer may rewrite an IN or EXISTS subquery as a join, so compare the plan rather than judging performance from syntax alone.
Exercise
Rewrite this DELETE so it removes customers with no orders and remains safe when orders.customerid can be NULL: DELETE FROM customers WHERE id NOT IN (SELECT customerid FROM orders);
Show answer
DELETE FROM customers AS c WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id);