Sub topic 9
Deleting Rows That Have No Match
This chapter covers anti-join deletes: removing rows from one table because no related row exists in another table. It assumes you can write SELECT, WHERE, and INNER JOIN, and that you know single-table UPDATE and DELETE. It also assumes you have seen DELETE ... USING and subqueries in WHERE. The examples reuse the customers, orders, products, and price_updates tables from earlier chapters.
Why DELETE ... USING cannot do this
DELETE ... USING works like an inner join. PostgreSQL pairs each target row with the rows of the USING table that satisfy the WHERE condition, and it deletes the target rows that got at least one pair. A target row with no partner never appears in the joined result, so the statement never sees it.
That makes "delete the orders whose customer does not exist" impossible to write with USING alone. You would need to ask about rows that are missing from the join, and an inner join drops exactly those rows.
A pattern that finds rows without a match is called an anti-join. SQL has no ANTI JOIN keyword. You write an anti-join with NOT EXISTS, NOT IN, or a LEFT JOIN filtered for NULL. Only the first of these is a safe default for deletes.
The NOT EXISTS pattern
Here is the standard form. It deletes every order whose customer_id has no matching row in customers:
DELETE FROM orders AS o
WHERE NOT EXISTS (
SELECT 1 FROM customers AS c WHERE c.id = o.customer_id
);Read it from the inside out. For each row of orders, PostgreSQL runs the subquery with o.customer_id filled in. The subquery is correlated, which means it refers to a column of the outer row. If the subquery finds a customer, EXISTS is true, NOT EXISTS is false, and the order stays. If it finds nothing, the order is deleted.
The SELECT 1 does not matter. EXISTS only checks whether any row comes back, so the select list is ignored. Many people write SELECT 1 to make that clear.
In practice the foreign key orders.customer_id REFERENCES customers (id) already prevents orphaned orders, so this statement would delete nothing in the sample schema. Orphans appear in tables without foreign keys, in data loaded with constraints disabled, and in legacy databases. The pattern is the same in all of those cases.
The diagram below shows how the three outcomes divide the rows.
Alternative 1: NOT IN and its NULL trap
You can write the same delete with NOT IN:
DELETE FROM orders
WHERE customer_id NOT IN (SELECT id FROM customers);This looks simpler, but it behaves differently when the subquery can return a NULL. SQL uses three-valued logic: a comparison with NULL is neither true nor false but unknown. x NOT IN (1, 2, NULL) expands to x <> 1 AND x <> 2 AND x <> NULL. The last term is unknown, so the whole expression can never be true. WHERE keeps only rows where the condition is true, so the statement deletes nothing.
In this example customers.id is a primary key and cannot be NULL, so NOT IN works. But the safety depends on the column definition, and a later schema change could break it silently. A NOT IN delete that suddenly removes zero rows is hard to notice. NOT EXISTS has no such trap, because it tests whether a row is found and never compares a value with NULL.
Alternative 2: LEFT JOIN ... IS NULL
A third form joins the tables with LEFT JOIN and keeps the rows where the right side is empty. In a SELECT, it looks like this:
SELECT o.id
FROM orders AS o
LEFT JOIN customers AS c ON c.id = o.customer_id
WHERE c.id IS NULL;The LEFT JOIN keeps every order and fills the customer columns with NULL when no customer matches. The WHERE c.id IS NULL then keeps only those unmatched orders.
DELETE has no LEFT JOIN clause, so you cannot paste this form into a delete directly. You can use it as a preview query, or move it into a subquery:
DELETE FROM orders
WHERE id IN (
SELECT o.id
FROM orders AS o
LEFT JOIN customers AS c ON c.id = o.customer_id
WHERE c.id IS NULL
);This works, but it is longer than NOT EXISTS and gives the planner no advantage. PostgreSQL recognizes both forms as an anti-join and normally produces the same plan for them. Use the LEFT JOIN form to preview and NOT EXISTS to delete, or use one form for both so that the preview matches the delete.
| Form | Works in DELETE directly | NULL trap | Notes |
|---|---|---|---|
| `NOT EXISTS` | Yes | No | Default choice |
| `NOT IN (subquery)` | Yes | Yes | Safe only if the column is `NOT NULL` |
| `LEFT JOIN ... IS NULL` | No, needs a wrapping subquery | No | Good for previews |
Adding conditions to the subquery
Anti-joins often need more than "no row exists". Suppose you want to delete products that have never been ordered. The sample schema has no order lines, so use a related example from the schema you have: delete customers who have no orders and are already closed.
DELETE FROM customers AS c
WHERE c.status = 'closed'
AND NOT EXISTS (
SELECT 1 FROM orders AS o WHERE o.customer_id = c.id
);The first condition filters the target table. The NOT EXISTS condition filters on the related table. Put conditions about the related rows inside the subquery. For instance, to delete customers who have no open orders, which still allows them to have other orders, add the extra filter inside:
DELETE FROM customers AS c
WHERE c.status = 'closed'
AND NOT EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
AND o.status = 'open'
);If this raises a foreign key violation, the customer still has non-open orders that reference it. The constraint stops the delete, which is the intended protection. You would first have to delete or archive those orders.
Previewing an anti-join delete
An anti-join is easy to get subtly wrong, because a typo in the correlation condition changes which rows count as unmatched. Before running the delete, run the same logic as a SELECT:
SELECT o.id, o.customer_id
FROM orders AS o
WHERE NOT EXISTS (
SELECT 1 FROM customers AS c WHERE c.id = o.customer_id
);Then run the delete inside a transaction with RETURNING, so you see the removed rows and can still roll back:
BEGIN;
DELETE FROM orders AS o
WHERE NOT EXISTS (
SELECT 1 FROM customers AS c WHERE c.id = o.customer_id
)
RETURNING o.id, o.customer_id;
-- Check the rows returned, then:
ROLLBACK; -- or COMMIT;Common mistakes
- Writing the correlation condition wrongly. If the subquery says
WHERE c.id = c.idor leaves out the link to the outer row, the subquery either always or never finds a row. A subquery that always finds a row deletes nothing. A subquery that never finds one deletes every row of the target table. Always preview. - Using
NOT INon a nullable column. See the warning above. - Forgetting the alias in the subquery. Without aliases,
idcan refer to the wrong table. Alias both tables and qualify every column. - Expecting
USINGto find unmatched rows. It cannot. UseNOT EXISTS.
Exercise
The table contacts has a column company_id, and companies has a primary key id. Write a DELETE that removes every contact whose company_id has no matching row in companies, and explain why you would not write it with DELETE ... USING.
Show answer
DELETE FROM contacts AS ct WHERE NOT EXISTS (SELECT 1 FROM companies AS co WHERE co.id = ct.company_id); DELETE ... USING behaves like an inner join, so it only sees contacts that do have a matching company. Contacts with no match never appear in the joined rows, so USING cannot select them.
Exercise
A colleague writes DELETE FROM orders WHERE customer_id NOT IN (SELECT manager_id FROM staff); and the statement reports DELETE 0, although you know many orders have no matching staff member. The column staff.manager_id allows NULL. What is the likely cause, and what is the fix?
Show answer
At least one row in staff has a NULL managerid. NOT IN then evaluates to unknown for every order, so no row is deleted. Rewrite it with NOT EXISTS: DELETE FROM orders AS o WHERE NOT EXISTS (SELECT 1 FROM staff AS s WHERE s.managerid = o.customerid); or add WHERE managerid IS NOT NULL to the subquery.