SQL DELETE FROM WHERE — Removing Rows Safely
How to delete rows from a table with DELETE FROM WHERE. Covers cascading deletes, DELETE with JOIN, TRUNCATE, and safety practices.
DML Commands
Detailed Explanation
Deleting Data
The DELETE statement removes rows from a table. Like UPDATE, forgetting the WHERE clause deletes all rows.
Basic Delete
DELETE FROM employees
WHERE id = 42;
Delete with Subquery
DELETE FROM employees
WHERE department_id IN (
SELECT id FROM departments WHERE is_archived = true
);
Delete with JOIN
PostgreSQL uses USING:
DELETE FROM employees e
USING departments d
WHERE e.department_id = d.id
AND d.name = 'Legacy'
RETURNING e.id, e.name;
MySQL uses JOIN:
DELETE e FROM employees e
JOIN departments d ON e.department_id = d.id
WHERE d.name = 'Legacy';
TRUNCATE vs DELETE
| Feature | DELETE | TRUNCATE |
|---|---|---|
| WHERE clause | Yes | No (all rows) |
| Triggers fired | Yes | No |
| Can ROLLBACK | Yes (in transaction) | Depends on DB |
| Speed | Slower (row-by-row) | Faster (page-level) |
| Resets auto-increment | No | Yes (MySQL, PostgreSQL) |
-- Remove all rows quickly
TRUNCATE TABLE temp_imports;
Cascading Deletes
If the table has foreign keys defined with ON DELETE CASCADE, deleting a parent row automatically deletes related child rows:
-- When departments table has: ON DELETE CASCADE
DELETE FROM departments WHERE id = 5;
-- All employees in department 5 are also deleted
Safety Checklist
- Run a
SELECTwith the same WHERE first to verify scope. - Wrap in a transaction (
BEGIN ... ROLLBACK / COMMIT). - Back up the table if deleting large volumes.
Use Case
You need to purge old or inactive records from a table, such as removing soft-deleted users after a retention period, or cleaning up temporary import data.