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)

idfirst_namedepartment_id
1Ada1
2Bob1
3Chen2
5Eli1

Sample Use Cases (3)

1) Delete rows with salary < 85000

idfirst_namesalary
1Ada120000
2Bob90000
4Dee110000
5Eli130000

2) Delete employees with NULL hired_at

idfirst_namehired_at
1Ada2021-01-10 10:00:00
2Bob2021-05-05 09:30:00
4Dee2022-03-01 12:00:00
5Eli2020-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.

idfirst_namedepartment_id
1Ada1
2Bob1
4Dee3
5Eli1