SQL · Chapter 9 of 42
SQL DELETE
DELETE removes rows. Like UPDATE, always include a WHERE — otherwise every row disappears.
`DELETE FROM table WHERE condition;`
Syntax
DELETE FROM table WHERE condition;TRUNCATE vs DELETE
`TRUNCATE` deletes ALL rows fast, resets auto-increment, and usually cannot be rolled back per-row.
Cascading deletes
Foreign keys can be defined with `ON DELETE CASCADE` so deleting a parent removes child rows automatically.
Example 1 (sql)
DELETE FROM users WHERE last_login < '2020-01-01';Output
12 rows deletedRemove inactive users.
Example 2 (sql)
-- DANGER: deletes every row!
DELETE FROM users;Output
all rows deletedOmit WHERE at your peril.
Key points
- Missing WHERE = delete ALL.
- TRUNCATE is faster for wiping a whole table.
- Wrap in a transaction so you can ROLLBACK.
- ON DELETE CASCADE removes related child rows.
💡 Note: Consider a 'soft delete' pattern — add a `deleted_at` column instead of physically removing rows. Great for auditing.
