Changing Data · Problem 116 of 118

Delete Customers with No Activity

HardChanging DataShop data

Delete every customer who has no orders and no reviews. Customers with at least one order or at least one review must stay (and the database would refuse to delete them anyway, because other tables point to them).

Check query. After your statements run, this query is run on the changed data and its result is compared with the expected one:

SELECT COUNT(*) AS customers,
       SUM(CASE WHEN EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id) THEN 1 ELSE 0 END) AS with_orders
FROM customers AS c;
Hint 1

Two NOT EXISTS conditions joined with AND.

Reference solution

DELETE FROM customers
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = customers.customer_id)
  AND NOT EXISTS (SELECT 1 FROM reviews AS r WHERE r.customer_id = customers.customer_id);

In a DELETE, the table name itself is the "outer row" that the correlated subquery refers to (customers.customer_id). When the wrong version fails with FOREIGN KEY constraint failed, that is the database protecting you from deleting customers with orders. Never switch foreign keys off to "make the error go away": it means the condition is wrong.

Another way. NOT IN also works here, because customer_id is never NULL in those tables. NOT EXISTS is the safer habit.

DELETE FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders)
  AND customer_id NOT IN (SELECT customer_id FROM reviews);