DSA Factory
Free SQL queries lessonsSQL queries · Stage 5 · Changing data · Step 3

Remove rows with DELETE

Delete just the rows you mean to, and check before you do. About 8 minutes.

DELETE FROM … WHERE

DELETE removes whole rows. The table stays, with fewer rows. Like UPDATE, it needs a WHERE, and without one it removes every row.

There's no column list, because a row can't be partly deleted. If you only want to clear a value, that's an UPDATE setting it to NULL.

DELETE without WHERE: empties the whole table.
In code
DELETE FROM coupons
WHERE expires_day < 50
   OR used = 1;
Delete the expired or used coupons
coupons
idcodeexpires_dayused
1SAVE10300
2NEW20900
3FREESHIP801
4FLASH101

SAVE10 expires on day 30, before 50. The OR passes, so the row is deleted.

Move 1 of 4

Look first, and think about keeping

Before a DELETE, run the same WHERE as a SELECT. Count the rows and read a few. If the numbers surprise you, you've found a mistake for free.

Also ask whether you should delete at all. Orders, payments and users are often kept and flagged with a deleted_at column instead, so a mistake can be undone and history stays. And mind the brackets when a condition mixes AND with OR.

SELECT first: same WHERE, then DELETE.
In code
SELECT COUNT(*)
FROM coupons
WHERE expires_day < 50 OR used = 1;
Quick check

What does DELETE FROM coupons; (with no WHERE) do?

  1. ARemoves every row but keeps the empty table
  2. BRemoves the table itself
  3. CNothing, because it needs a WHERE
Show the answer

Removes every row but keeps the empty table. No WHERE matches all rows. The table and its columns remain.

Your problem

Clear the old coupons

The coupons table has one row per coupon, the day it expires, and used set to 1 once it has been redeemed. Today is day 50. Delete every coupon that has expired (expires_day before 50) or has been used.

Tables
coupons(id, code, expires_day, used)

Up to 2,000 coupons

Write the query in your browserFree account, no card. Your query runs on real tables, with hints if you get stuck, and your progress is saved.
Sign up free to solve