Deleting Rows with DELETE

DELETE deletes rows from a table. Ava Green has asked the shop to remove her reviews:

DELETE FROM reviews
WHERE customer_id = 5;

After DELETE FROM comes the table, and WHERE says which rows to delete. Results shows Rows changed: 2, because Ava wrote two reviews, and a query shows that 23 of the 25 reviews are left:

SELECT COUNT(*) AS reviews
FROM reviews;
reviews
23

DELETE always deletes whole rows, so it has no list of columns: DELETE title FROM games is an error, and so is DELETE * FROM games, which you may come across in other databases. To remove just one value from a row, use UPDATE: SET city = NULL.

And just like an UPDATE, a DELETE without WHERE deletes every row: after DELETE FROM reviews;, the table is empty. It still exists, with its columns, but it has no rows. So try out the WHERE in a SELECT first, as you've learned.

Some rows can't be deleted. Try deleting the refunded order 7:

DELETE FROM orders
WHERE id = 7;
Error on line 1: FOREIGN KEY constraint failed

The row of order_items with order 7 points at the order with its foreign key order_id. If the order disappeared, the item would point at an order that doesn't exist. The database protects you from that: it refuses to delete a row that another row points at. Its message doesn't say which row it is, so you have to find it yourself. Think of which tables have a foreign key to this one.

The solution is to delete the rows that point at it first, and then the row itself:

DELETE FROM order_items
WHERE order_id = 7;

DELETE FROM orders
WHERE id = 7;

The order matters: first the rows that point, and last the row they point at. The same protection works for UPDATE too: it can't make a foreign key point at a row that doesn't exist either.

Instructions

Robot Rebellion (ID 18) has been canceled: it will never come out. Delete it from games, and below, show the ID and title of the games that haven't come out yet (their released is NULL), sorted by ID. Only one is left:

idtitle
19Mystery Manor

Isla Young (customer 9) has asked the shop to delete her account with everything that belongs to it. Delete her from customers, but first, everything that points at her: her reviews, her orders, and before the orders, their items. (You'll find her orders in the Tables tab, or let a subquery find them.) Then show the ID and name of the customers with the IDs 8 to 10, sorted by ID:

idname
8Leo Walker
10Oscar King

Finally, make sure that nothing else is gone: show how many orders, order items and reviews are left, in one row with the columns orders, items and reviews. Each column can be a subquery with COUNT(*), and a query that has no table of its own doesn't need FROM. Compared with the start, one order, one item and one review should be gone:

ordersitemsreviews
294124

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/9