Sub topic 11
Using EXISTS in UPDATE and DELETE
This chapter shows how to use EXISTS and NOT EXISTS in UPDATE and DELETE statements. It assumes you can write a correlated subquery and use EXISTS and NOT EXISTS in a SELECT. You should also know basic transaction commands (START TRANSACTION, COMMIT, ROLLBACK). The examples use the customers, orders, and order_items tables from earlier chapters. Some examples also assume extra columns, which each example names.
Why EXISTS fits data modification
An UPDATE or DELETE has a WHERE clause, and that clause decides which rows change. Any condition you can write in a SELECT ... WHERE also works there. This includes EXISTS and NOT EXISTS.
Both statements often need a condition based on another table:
- Delete customers who have never ordered.
- Mark customers as inactive if they have no recent orders.
- Remove line items that belong to cancelled orders.
These are presence and absence questions. A join would be awkward here because UPDATE and DELETE change one target table, and the join syntax differs a lot between databases. A correlated EXISTS subquery is close to standard SQL and works in all major databases.
The correlation works as it does in a SELECT. For each row of the target table, the database evaluates the subquery with that row's values. The row is changed only if the WHERE condition is true.
The diagram shows the logical model. A real database may run the query differently, for example as an anti-join, but the result must match this model.
DELETE with NOT EXISTS
This statement deletes customers who have no orders:
DELETE FROM customers
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = customers.customer_id
);The subquery refers to the target table by its name, customers.customer_id. The o alias on orders keeps the two tables apart.
Preview with SELECT first
A DELETE cannot be undone once it is committed. Before you run one, turn it into a SELECT that uses the same WHERE clause:
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);Check the rows and the count. If the result looks wrong, you have lost nothing. The WHERE clauses are written differently only because of the alias. The logic is identical.
Run it inside a transaction
You can also run the real statement inside a transaction and check the result before you commit:
START TRANSACTION;
DELETE FROM customers
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = customers.customer_id
);
-- Check the reported row count and look at the table here.
-- If the count is wrong, run ROLLBACK instead of COMMIT.
COMMIT;Most clients print the number of affected rows after a DELETE. Compare it with the count from your preview. If they differ, run ROLLBACK.
UPDATE with EXISTS and NOT EXISTS
UPDATE uses the same pattern. Suppose customers has a status column. This statement marks customers with no orders since the start of 2026 as inactive:
UPDATE customers
SET status = 'inactive'
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = customers.customer_id
AND o.order_date >= '2026-01-01'
);The extra date condition goes inside the subquery. The subquery asks whether this customer has a recent order, and NOT EXISTS selects those for whom the answer is no. A customer with no orders at all is also marked inactive, because the subquery finds nothing for them either.
If you want only customers who have ordered before, but not recently, you need two conditions:
UPDATE customers
SET status = 'lapsed'
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = customers.customer_id
)
AND NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = customers.customer_id
AND o.order_date >= '2026-01-01'
);Both subqueries use the alias o. That is allowed because each alias is local to its own subquery.
Copying a value with a correlated scalar subquery
You often want to set a column to a value computed from related rows. Suppose customers has a last_order_date column. A correlated scalar subquery in the SET clause can fill it:
UPDATE customers
SET last_order_date = (
SELECT MAX(o.order_date)
FROM orders o
WHERE o.customer_id = customers.customer_id
);This has a side effect that surprises many people. The SET expression is evaluated for every row of customers. For a customer with no orders, MAX returns NULL, so the statement overwrites any existing last_order_date with NULL. If you only want to touch customers who have orders, add an EXISTS guard:
UPDATE customers
SET last_order_date = (
SELECT MAX(o.order_date)
FROM orders o
WHERE o.customer_id = customers.customer_id
)
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = customers.customer_id
);The two subqueries do different jobs. The one in SET computes the value. The one in WHERE selects which rows are updated.
Keep two rules in mind for scalar subqueries in SET:
- The subquery must return at most one row for each target row. An aggregate such as
MAXguarantees this. A subquery that returns two rows causes an error in most databases. - If it returns zero rows, the result is
NULL, not an error.
Deleting child rows before parent rows
Foreign keys often control the order of deletes. Suppose orders has a status column and order_items has a foreign key to orders. To remove cancelled orders you must delete their items first:
DELETE FROM order_items
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.order_id = order_items.order_id
AND o.status = 'cancelled'
);
DELETE FROM orders
WHERE status = 'cancelled';Run both statements in one transaction. If the second one fails, the rollback restores the items too. Here EXISTS filters the child table using a condition that lives only on the parent table. You do not need a join, and you cannot delete the parent first because the foreign key would reject it (unless the key is defined with ON DELETE CASCADE).
Deleting duplicates in the same table
EXISTS can compare a table with itself. This statement removes duplicate customers by email and keeps the one with the lowest customer_id:
DELETE FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM customers d
WHERE d.email = c.email
AND d.customer_id < c.customer_id
);A row is deleted if another row has the same email and a smaller id. The row with the smallest id for each email has no such partner, so it stays.
Two details matter:
- Rows with a
NULLemail are never deleted. The comparisond.email = c.emailis not true when either side isNULL. Decide separately how you want to handle those rows. - MySQL rejects this form with error 1093, because it does not allow a subquery on the table being modified. The usual workaround is to wrap the subquery in a derived table or to use a multi-table
DELETE ... JOIN.
Syntax differences between databases
The EXISTS logic is portable, but the way you name the target table in DELETE and UPDATE is not.
| Database | Aliasing the target in DELETE | Notes |
|---|---|---|
| PostgreSQL | `DELETE FROM customers AS c WHERE ...` | Also has `USING` for joins. |
| MySQL | `DELETE c FROM customers AS c WHERE ...` | A subquery on the same table fails with error 1093. |
| SQL Server | `DELETE c FROM customers AS c WHERE ...` | The alias comes after the keyword `DELETE`. |
| Oracle | `DELETE FROM customers c WHERE ...` | Alias without `AS`. |
Using the full table name, as in customers.customer_id, avoids alias questions in the simple cases. Check your database's documentation for the exact rules in your version. The preview SELECT is still the best way to confirm the logic before you adapt the syntax.
Common errors
- Missing correlation. If you forget
o.customer_id = customers.customer_id, the subquery no longer depends on the outer row. ThenNOT EXISTSis either true for every row or false for every row. ADELETEcould remove the whole table or nothing at all. - Overwriting with NULL. A scalar subquery in
SETwithout anEXISTSguard sets unmatched rows toNULL. - Using NOT IN.
customer_id NOT IN (SELECT customer_id FROM orders)deletes nothing iforders.customer_idcontains aNULL. WithNOT EXISTSyou avoid that. - Wrong deletion order. Deleting a parent row first fails when child rows still refer to it.
- Skipping the preview. A
SELECTwith the sameWHEREclause costs seconds and catches most logic mistakes.
Concurrency and performance
A statement like DELETE ... WHERE NOT EXISTS checks the condition and removes rows in one statement, but another session can still insert an order for a customer between your preview and your delete. A foreign key from orders to customers would then reject the delete of that customer, or the delete would remove a customer who has just started ordering. In busy systems, run the statement in a transaction and consider locking the rows you plan to remove. How to do that depends on the database and isolation level, so check your documentation.
For speed, the rules from the indexing chapter apply here as well. The correlation column in the inner table needs an index:
CREATE INDEX idx_orders_customer_id ON orders (customer_id);Without it, the database may scan orders for each candidate customer. On a large table, a big DELETE can also hold locks and fill the transaction log for a long time. Consider deleting in batches if you are removing millions of rows.
Exercises
Exercise
A table products has a column active (boolean), and order_items has a column product_id. Write a statement that sets active to false for every product that has never appeared in any order item. Then name the first thing you should do before running it.
Show answer
UPDATE products SET active = FALSE WHERE NOT EXISTS ( SELECT 1 FROM orderitems oi WHERE oi.productid = products.product_id ); Before running it, run a SELECT with the same WHERE clause (using an alias such as p) to preview which products will change, and run the UPDATE inside a transaction so you can roll back if the row count is wrong.
Exercise
This statement is meant to store each customer's most recent order date, but it also erases existing values for customers who have no orders. Explain why, and fix it. UPDATE customers SET lastorderdate = ( SELECT MAX(o.orderdate) FROM orders o WHERE o.customerid = customers.customer_id );
Show answer
The SET subquery is evaluated for every customer. For a customer with no orders, MAX returns NULL, so lastorderdate is overwritten with NULL. Add a WHERE EXISTS guard so that only customers with at least one order are updated: UPDATE customers SET lastorderdate = ( SELECT MAX(o.orderdate) FROM orders o WHERE o.customerid = customers.customerid ) WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customerid = customers.customer_id );