Hone

Lessons · SQL · DELETE needs WHERE

DELETE needs a WHERE

DELETE FROM table removes rows matching WHERE. Without WHERE it removes every row.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

This has ended careers. The safe habit is worth learning before you have production access.

How to think about it

What would a SELECT with this WHERE return? Write the SELECT with the same WHERE first, check the rows, then change SELECT * to DELETE.

Worked example

SELECT * FROM sessions WHERE expires < '2024-01-01';
Look first.
DELETE FROM sessions WHERE expires < '2024-01-01';
Same WHERE, now delete.

Your turn

Delete only cancelled orders.

DELETE FROM orders  status = 'cancelled';

The trap

Running a DELETE inside a transaction is the other guard: BEGIN, DELETE, check the count, COMMIT or ROLLBACK.

Practise DELETE needs WHERE on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.