Changing Data · Problem 115 of 118

Remove Lines of Cancelled Orders

MediumChanging DataShop data

Delete the rows of order_items that belong to orders whose status is 'cancelled'. Keep the orders and every other line.

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

SELECT o.status, COUNT(*) AS lines
FROM order_items AS oi
JOIN orders AS o ON o.order_id = oi.order_id
GROUP BY o.status
ORDER BY o.status;
Hint 1

DELETE FROM order_items WHERE order_id IN (SELECT ...).

Reference solution

DELETE FROM order_items
WHERE order_id IN (SELECT order_id FROM orders WHERE status = 'cancelled');

Child rows must be deleted before their parents. order_items.order_id is a foreign key to orders, and the database refuses to delete an order that still has lines (FOREIGN KEY constraint failed). The subquery finds the parent rows to look at, the DELETE removes the children. This is exactly why foreign keys are valuable: they stop you from creating orphans.