SQL - DELETE
Overview
DELETE removes rows based on a filter. TRUNCATE removes all rows and is typically faster but more restrictive.
DELETE FROM employees WHERE department_id = 3;
-- TRUNCATE TABLE employees;  -- be careful
DELETE FROM employees WHERE department_id = 3;
-- TRUNCATE TABLE employees;  -- be careful
DELETE FROM employees WHERE department_id = 3;
-- SQLite has no TRUNCATE; use DELETE without WHERE
-- and optionally VACUUM to reclaim file space.
Prerequisite
Load the Standard Test Data.
Expected Output (live; wrapped in a transaction)
| id | first_name | department_id | 
|---|---|---|
| 1 | Ada | 1 | 
| 2 | Bob | 1 | 
| 3 | Chen | 2 | 
| 5 | Eli | 1 | 
Sample Use Cases (3)
1) Delete rows with salary < 85000
| id | first_name | salary | 
|---|---|---|
| 1 | Ada | 120000 | 
| 2 | Bob | 90000 | 
| 4 | Dee | 110000 | 
| 5 | Eli | 130000 | 
2) Delete employees with NULL hired_at
| id | first_name | hired_at | 
|---|---|---|
| 1 | Ada | 2021-01-10 10:00:00 | 
| 2 | Bob | 2021-05-05 09:30:00 | 
| 4 | Dee | 2022-03-01 12:00:00 | 
| 5 | Eli | 2020-11-20 15:15:00 | 
3) Delete by department using join
In SQLite, use subquery; in MySQL/SQL Server, you can delete with join syntax.
| id | first_name | department_id | 
|---|---|---|
| 1 | Ada | 1 | 
| 2 | Bob | 1 | 
| 4 | Dee | 3 | 
| 5 | Eli | 1 |