Sub topic 9
Deleting Rows That Have No Match
The anti-join pattern
Prerequisites: you should know SELECT, WHERE, INNER JOIN, table aliases, and basic DELETE statements.
Sometimes you need to delete rows because a related row does not exist. This is called an anti-join. For example, you might remove log records whose user account was deleted, or remove imported records whose referenced product is missing.
DELETE ... USING is useful when a matching row identifies what to delete. It does not directly express “delete when no match exists.” For that case, use NOT EXISTS.
DELETE FROM orders AS o
WHERE NOT EXISTS (
SELECT 1
FROM customers AS c
WHERE c.id = o.customer_id
);The inner query is correlated because it refers to o.customer_id from the outer DELETE. PostgreSQL checks the subquery for each order:
- If a customer with that ID exists,
EXISTSis true, soNOT EXISTSis false. The order remains. - If no such customer exists,
NOT EXISTSis true. PostgreSQL deletes the order.
The SELECT 1 value does not matter. EXISTS only checks whether the subquery returns at least one row.
Why `NOT IN` can be dangerous
You can sometimes write the same condition with NOT IN:
DELETE FROM orders
WHERE customer_id NOT IN (
SELECT id FROM customers
);This becomes unsafe when the subquery can return NULL. SQL uses three-valued logic: a comparison involving NULL is unknown, not true. If the subquery contains a null value, NOT IN may match no rows at all.
NOT EXISTS avoids this particular NULL problem because it tests whether a matching row exists. Prefer it when the relationship or nullable columns are involved.
A `LEFT JOIN` alternative
A LEFT JOIN keeps every row from the left table, including rows with no match. You can then test the right table's key for NULL.
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id;That statement deletes matching orders, so it is not an anti-join. PostgreSQL does not allow the target table to be written as a LEFT JOIN directly in DELETE ... USING. Use NOT EXISTS for the clearest PostgreSQL form.
If you first preview the rows with a SELECT, the intended anti-join is easy to inspect:
SELECT o.*
FROM orders AS o
WHERE NOT EXISTS (
SELECT 1
FROM customers AS c
WHERE c.id = o.customer_id
);Constraints and safe execution
A foreign key normally prevents an order from referring to a missing customer. Therefore, the example may return zero rows in a healthy schema. That is useful: zero rows can confirm that the constraint is protecting your data.
Run a bulk delete inside a transaction while you inspect the affected rows:
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;
ROLLBACK;Use COMMIT instead of ROLLBACK only after checking the returned rows. Add indexes on the columns used for matching, such as customers.id and orders.customer_id, when the tables are large.
Exercise
Why is NOT EXISTS usually safer than NOT IN for deleting rows with no related match?
Show answer
NOT EXISTS checks whether a matching row exists and does not become unknown merely because the subquery contains NULL.