SQL DELETE
What you will learn
- How
DELETE FROM ... WHEREremoves rows - How to count before you delete
- Why a foreign key can refuse a delete
- Why marking rows instead of deleting is often better
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). The changes happen only in your browser's copy of the data; Reset data puts everything back. Run the cells from top to bottom.
1. DELETE with WHERE
DELETE FROM table WHERE condition removes the rows that match. As with UPDATE, count them first:
Reviews with the lowest rating:
SELECT COUNT(*) AS one_star_reviews FROM reviews WHERE rating = 1;
one_star_reviews
----------------
21
(1 row)
DELETE FROM reviews WHERE rating = 1;
(21 rows changed)
SELECT COUNT(*) AS one_star_reviews_now FROM reviews WHERE rating = 1;
one_star_reviews_now
--------------------
0
(1 row)
Audit log entries without a note:
SELECT COUNT(*) AS entries_without_note FROM audit_log WHERE note IS NULL;
entries_without_note
--------------------
29
(1 row)
DELETE FROM audit_log WHERE note IS NULL;
(29 rows changed)
SELECT COUNT(*) AS entries_without_note_now FROM audit_log WHERE note IS NULL;
entries_without_note_now
------------------------
0
(1 row)
Attendance records marked absent on one day:
SELECT COUNT(*) AS absent_rows FROM attendance WHERE status = 'absent';
absent_rows
-----------
423
(1 row)
DELETE FROM attendance WHERE status = 'absent';
(423 rows changed)
SELECT COUNT(*) AS absent_rows_now FROM attendance WHERE status = 'absent';
absent_rows_now
---------------
0
(1 row)
The delete reports how many rows it removed. It should equal the first count.
2. Delete one row by its key
To remove one row, use the primary key in the condition:
SELECT review_id, rating FROM reviews ORDER BY review_id LIMIT 3;
review_id rating
--------- ------
1 3
2 3
3 4
(3 rows)
DELETE FROM reviews WHERE review_id = (SELECT MIN(review_id) FROM reviews);
(1 row changed)
SELECT review_id, rating FROM reviews ORDER BY review_id LIMIT 3;
review_id rating
--------- ------
2 3
3 4
4 5
(3 rows)
SELECT log_id, action FROM audit_log ORDER BY log_id LIMIT 3;
log_id action
------ ------
3 update
4 update
5 insert
(3 rows)
DELETE FROM audit_log WHERE log_id = (SELECT MIN(log_id) FROM audit_log);
(1 row changed)
SELECT log_id, action FROM audit_log ORDER BY log_id LIMIT 3;
log_id action
------ ------
4 update
5 insert
9 insert
(3 rows)
SELECT assignment_id, student_id, points FROM submissions ORDER BY assignment_id, student_id LIMIT 3;
assignment_id student_id points
------------- ---------- ------
1 16 47.8
1 27 84.3
1 56 87.1
(3 rows)
DELETE FROM submissions WHERE assignment_id = 1 AND student_id = 16;
(1 row changed)
SELECT assignment_id, student_id, points FROM submissions ORDER BY assignment_id, student_id LIMIT 3;
assignment_id student_id points
------------- ---------- ------
1 27 84.3
1 56 87.1
1 161 79.7
(3 rows)
3. A foreign key can refuse the delete
A row that other rows point to cannot be deleted while they do (Database Fundamentals, lesson 3.5). The database protects the link:
Customer 1 has orders:
DELETE FROM customers WHERE customer_id = 1;
IntegrityError: FOREIGN KEY constraint failed
Customer 1 has accounts:
DELETE FROM customers WHERE customer_id = 1;
IntegrityError: FOREIGN KEY constraint failed
Student 1 has enrollments:
DELETE FROM students WHERE student_id = 1;
IntegrityError: FOREIGN KEY constraint failed
FOREIGN KEY constraint failed means some child row still refers to it. Delete (or move) the children first, or keep the parent. The right answer depends on the business; the next section gives a common one.
4. Marking instead of deleting
Many systems almost never delete important rows. They add a column that marks a row as inactive and filter it out. This is called a soft delete (Database Fundamentals, lesson 10.3). The history stays, links stay valid, and the change can be undone:
customers.is_active is such a column:
UPDATE customers SET is_active = 0 WHERE customer_id = 1;
(1 row changed)
SELECT customer_id, first_name, is_active FROM customers WHERE customer_id = 1;
SELECT COUNT(*) AS active_customers FROM customers WHERE is_active = 1;
customer_id first_name is_active
----------- ---------- ---------
1 Vik 0
(1 row)
active_customers
----------------
393
(1 row)
accounts.status can be set to closed instead of deleting the account:
UPDATE accounts SET status = 'closed' WHERE account_id = 1;
(1 row changed)
SELECT account_id, status FROM accounts WHERE account_id = 1;
SELECT COUNT(*) AS open_accounts FROM accounts WHERE status = 'open';
account_id status
---------- ------
1 closed
(1 row)
open_accounts
-------------
403
(1 row)
Instead of deleting an enrollment, clear the grade and keep the row (a made-up rule):
UPDATE enrollments SET grade = NULL WHERE student_id = 1 AND section_id = 30;
(1 row changed)
SELECT student_id, section_id, grade FROM enrollments WHERE student_id = 1 AND section_id = 30;
student_id section_id grade
---------- ---------- -----
1 30 NULL
(1 row)
Queries then add the filter (WHERE is_active = 1) wherever only live rows should appear.
5. The danger: no WHERE
DELETE FROM table; with no WHERE removes every row. The table remains, empty. Try it on a scratch copy, not on a real table:
CREATE TABLE review_copy AS SELECT * FROM reviews;
SELECT COUNT(*) AS rows_before FROM review_copy;
rows_before
-----------
563
(1 row)
DELETE FROM review_copy;
(563 rows changed)
SELECT COUNT(*) AS rows_after FROM review_copy;
rows_after
----------
0
(1 row)
CREATE TABLE log_copy AS SELECT * FROM audit_log;
SELECT COUNT(*) AS rows_before FROM log_copy;
rows_before
-----------
90
(1 row)
DELETE FROM log_copy;
(90 rows changed)
SELECT COUNT(*) AS rows_after FROM log_copy;
rows_after
----------
0
(1 row)
CREATE TABLE attendance_copy AS SELECT * FROM attendance;
SELECT COUNT(*) AS rows_before FROM attendance_copy;
rows_before
-----------
5589
(1 row)
DELETE FROM attendance_copy;
(5589 rows changed)
SELECT COUNT(*) AS rows_after FROM attendance_copy;
rows_after
----------
0
(1 row)
Once the work is saved, a delete is permanent. Only a backup can bring the rows back (Database Fundamentals, lesson 8.1). Lesson 5.5 shows ROLLBACK, which can undo a mistake before it is saved.
In other databases. Many databases have a separate
TRUNCATE TABLEstatement for emptying a table quickly. SQLite does not: its documentation says it has noTRUNCATEstatement and instead speeds up aDELETEwithoutWHERE(and withoutRETURNING, on a table without triggers). The details ofTRUNCATEdiffer between the databases that have it, so check the documentation of yours.
Worked example: remove old records safely
"Delete log entries older than 2020."
| Step | Do |
|---|---|
| 1 | SELECT COUNT(*) FROM log WHERE logged_on < '2020-01-01'; and note the number |
| 2 | SELECT * FROM log WHERE logged_on < '2020-01-01' LIMIT 10; and check the rows are the right ones |
| 3 | save a copy of the rows if they might be needed |
| 4 | DELETE FROM log WHERE logged_on < '2020-01-01'; |
| 5 | check that rows changed equals the count |
The table is made up.
Common mistakes
DELETEwithoutWHERE.- Deleting without counting first.
- Deleting a parent that children point to (the database refuses; do not work around it carelessly).
- Deleting when a "mark as inactive" would keep the history.
- No backup before a large delete.
Key takeaways
DELETE FROM t WHERE conditionremoves the matching rows; with noWHEREit removes all of them.- Count the rows with a
SELECTfirst, then compare withrows changed. - A foreign key refuses to delete a row that others point to.
- Marking rows inactive keeps the history and the links.
Practice
1. Write a delete for the review with id 10.
Show answer
DELETE FROM reviews WHERE review_id = 10;
2. What does DELETE FROM customers; do?
Show answer
It removes every row of the table (if no foreign key stops it).
3. Why did the delete of customer 1 fail?
Show answer
Other rows (orders, accounts or enrollments) still point to it, and the foreign key protects the link.
4. What is a soft delete?
Show answer
Marking a row as inactive (for example is_active = 0) instead of removing it.
5. How do you check how many rows a delete will remove?
Show answer
SELECT COUNT(*) FROM table WHERE condition with the same condition.
6. Can a deleted row be brought back after the work is saved?
Show answer
Only from a backup (or if it was copied elsewhere first).