Deleting Rows Safely with SQL DELETE
DELETE removes rows from a table. Preview the target rows first, and use a transaction when you need a rollback path.
DELETE
removes rows, and like
UPDATE
it obeys your
WHERE
clause, or deletes everything if you forget it.
The safe ritual is two steps: first
SELECT
the rows your filter matches and eyeball them, then run the same filter as a
DELETE. The starter below is that first step. Run it before you change anything.
-- 1. measure
select * from orders where status = 'cancelled';
-- 2. cut
delete from orders where status = 'cancelled'; Schema · Garden Shop Table · orders 6 columns · 24 rows
One row per order. Unshipped orders have a null shipped_date.
The shop purges cancelled orders. First run the starter to see which orders
are 'cancelled'. Then delete every order
with that status. Confirm the purge touched only those orders: return each
status with its count(*) as orders,
sorted by status.
Run your query to inspect the result.
Expected answer
- Columns: status, orders.
- Rows: 3 statuses, sorted by status. cancelled no longer appears.
- pending 3, processing 3, shipped 17: 23 orders, one fewer than before. A DELETE with no WHERE returns no rows at all.
Related
A checklist for changing the right rows.
Understand INSERT, UPDATE, and DELETE.
Add rows and confirm they landed.
Change existing rows safely.
Wrap risky changes so you can undo them.