…
…
SQL and Database Fundamentals · Lesson 36 / 41 · Changing data
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Only two students enrolled in the Data Structures section (offering 13) for 2026-Fall, so the section will be closed. Four sections from last term never got a student, and three students never enrolled in any course. All of them will be cleaned out, and deleted data does not come back, so every step needs care.
In lesson 34 you added rows to tables, and in lesson 35 you updated existing rows. The third job in data management is deleting rows, and it is the most dangerous of the three. A wrong UPDATE damages a value, but the row stays in place. A wrong DELETE removes the row completely. So this lesson teaches not only one command, but also the habits for using it safely.
In this lesson you will:
RETURNING.The deletion list for student services looks like this:
| To delete | Why | How many rows |
|---|---|---|
| Offering 13 (Data Structures, 2026-Fall) | Closing with two students | 1 offering |
| Enrollments of offering 13 | Meaningless once the offering closes | 2 enrollments |
| Offerings with no enrollments (2025-Fall) | Opened but got no students | 4 offerings |
| Students who never enrolled in a course | Entered by mistake | 3 students |
The command for deleting rows is DELETE. Its syntax is similar to UPDATE but shorter, because there is no value to change; a row either stays or goes:
OutputDELETE FROM table
WHERE condition;DELETE removes the rows that match the WHERE condition from the table. The condition can select a single row (WHERE id = 18) or hundreds of rows (WHERE midterm < 50). So what happens if you write no condition at all?
The enrollment table has 781 rows. What does DELETE FROM enrollment; do?
DELETE FROM enrollment;
Example 1 (case): DELETE without WHERE
DELETE FROM enrollment; SELECT COUNT(*) AS remaining FROM enrollment;
| remaining |
|---|
| 0 |
Four years of enrollment history disappeared in one line, and you did not even see an error. PostgreSQL cannot know what you meant; it does what the command says. Notice that this gives the same result as TRUNCATE enrollment; from lesson 33: TRUNCATE removes all rows with no condition, while DELETE can take a condition, but when the condition is forgotten it also removes all rows. The command that removes the table together with its structure is the DROP TABLE you know from lesson 33.
Let's start with the last row of the deletion list: students who never enrolled in a course. The NOT EXISTS pattern from lesson 21 is enough to find them. But before deleting, do one more thing: run a SELECT with the same condition and see the rows to be deleted with your own eyes.
The strength of this method is that you never touch the condition. The WHERE line you tested with SELECT stays exactly as it is; only the command at the start changes. So the rows SELECT shows and the rows DELETE removes are the same. In the cell below, the SELECT is ready. Run it and see the three students. Then:
1. Change only the first line to DELETE FROM student o; do not touch the WHERE line.
2. Remove the ORDER BY line (DELETE takes no sorting) and add RETURNING id, first_name, last_name; at the end. Are the deleted rows the same three students?
Try it now· not graded; doesn't affect progress
The result of the SELECT is:
| id | first_name | last_name |
|---|---|---|
| 13 | Yuki | Johansson |
| 60 | Hiro | Kim |
| 67 | Mohammed | Cohen |
When you change it to DELETE and add RETURNING, the same three students come back. In lesson 34 you saw that RETURNING shows the inserted row; with DELETE it shows the deleted rows one last time. The rows do not come in a particular order, but the set is the same: 13, 60, and 67. The count matters too. If SELECT said 3, DELETE should delete 3 rows; if DELETE reports an unexpected number, something is wrong with the condition.
Next is offering 13. The first command that comes to mind is to delete the offering row directly:
OutputDELETE FROM course_offering WHERE id = 13;
ERROR: update or delete on table "course_offering" violates foreign key constraint "enrollment_offering_id_fkey" on table "enrollment"PostgreSQL refused to delete the offering, because the enrollment table has two rows that refer to this offering. If the offering were deleted, those two enrollments would point to an offering that does not exist. The foreign keys you built in lesson 30 exist to prevent exactly this. The same thing happens in other places: deleting student 1, who has enrollments, stops with enrollment_student_id_fkey, and deleting instructor 1, who advises students, stops with a student_advisor_id_fkey error. Instructor 18, who teaches no course and advises no one, is deleted without trouble; no row refers to that instructor.
All the foreign keys in the case use the default behavior (NO ACTION): the delete behavior you chose in lesson 30 is working here and stops the delete to protect the referenced row. If these tables had been built with ON DELETE CASCADE, the command deleting the offering would silently delete both enrollments too; you would see no error and no count of how many rows went. A common mistake is to treat this error as an obstacle to get past: removing the constraint or widening the condition. But the error is a warning. It says, "Data depends on this row; decide what happens to it." The decision is either to delete the dependent rows on purpose first, or not to delete at all.
The decision for offering 13 has been made: the term has just started, the two students have no final exam and no letter grade yet, so their enrollments can be deleted. Put the four commands that close the offering safely in the right order:
Put the commands that safely close offering 13 in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
A deleted row does not wait somewhere. There is no recycle bin like the one on your computer; once the command finishes and the change becomes permanent, the row is gone. There are only two ways to get it back: a backup taken earlier, or undoing the change before it becomes permanent. You will learn the second in lesson 37. For the first you need nothing new: CREATE TABLE ... AS SELECT from lesson 28 copies the rows to be deleted in a single command. The WHERE of the backup is the same as the WHERE of the delete.
Example 2 (case): Take a backup, delete the children, then delete the parent row
CREATE TABLE deleted_enrollment AS SELECT * FROM enrollment WHERE offering_id = 13; DELETE FROM enrollment WHERE offering_id = 13; DELETE FROM course_offering WHERE id = 13; SELECT (SELECT COUNT(*) FROM deleted_enrollment) AS backup, (SELECT COUNT(*) FROM course_offering WHERE term_id = 3) AS fall_offerings;
| backup | fall_offerings |
|---|---|
| 2 | 19 |
The backup table holds two enrollments, and 19 offerings remain in 2026-Fall. As long as the backup table stays, a wrong delete can be undone. When you do not want a backup but still want to see what was deleted, there is RETURNING. The cell below deletes the enrollments of offering 13 and shows the student number and letter grade of the deleted rows. Run it: students 6 and 23 come back, and their letter grades are NULL because the term is still running. Then write RETURNING * and look at all the columns of the deleted rows.
Try it now· not graded; doesn't affect progress
RETURNING is not a backup: it shows the deleted rows on screen once and does not store them. When you close the screen, those rows are gone again. For an important delete, the two are used together: first the backup, then delete with RETURNING.
To delete offerings with no enrollments, the condition has to look at another table: "Is there an enrollment that refers to this offering?" This question is the job of the correlated subquery you learned in lesson 21.
Example 3 (case): Deleting empty offerings with NOT EXISTS
DELETE FROM course_offering a WHERE NOT EXISTS (SELECT 1 FROM enrollment k WHERE k.offering_id = a.id) RETURNING id, course_id, term_id;
Result (row order may vary):
| id | course_id | term_id |
|---|---|---|
| 27 | 17 | 1 |
| 12 | 8 | 1 |
| 51 | 32 | 1 |
| 35 | 22 | 1 |
All four offerings are from 2025-Fall (term 1). Because no enrollment refers to these offerings, no foreign key error appeared. PostgreSQL also lets you delete by joining another table with DELETE ... USING; in this course the subquery form is enough.
You could have written the same job with NOT IN. In lesson 20 you saw a trap of this operator; in DELETE that trap is even sneakier. Predict first:
In the condition WHERE id NOT IN (SELECT advisor_id FROM student), the subquery result also contains NULL values. How many rows does this condition select?
Example 4 (case): Finding the instructor who advises no one
SELECT COUNT(*) AS with_not_in FROM instructor WHERE id NOT IN (SELECT advisor_id FROM student);
| with_not_in |
|---|
| 0 |
The output is zero because 8 students have a NULL advisor_id. When you ask the same question with NOT EXISTS, the right answer comes: WHERE NOT EXISTS (SELECT 1 FROM student o WHERE o.advisor_id = t.id) finds 1 instructor, instructor 18. Thinking "NOT IN and NOT EXISTS always give the same result" is a common mistake; when the subquery can contain NULL, the two differ. In DELETE this means the command says DELETE 0 and shows no error. The rows you needed to delete stay in place and you think the job is done. When the condition looks at another table, use NOT EXISTS and see the count with a SELECT first.
In real systems, records such as students, orders, and invoices are often never deleted. Predict the reason first:
Why are records such as students or orders often not deleted in real systems?
A logical delete (soft delete) means marking a row as "gone" with a flag such as active = FALSE instead of deleting it. In lesson 33 you saw how to add an active column to students; now you see why that column exists.
Example 5 (case): Setting aside students with no enrollments without deleting them
ALTER TABLE student ADD COLUMN active BOOLEAN NOT NULL DEFAULT TRUE; UPDATE student SET active = FALSE WHERE id IN (13, 60, 67); SELECT COUNT(*) FILTER (WHERE active) AS active, COUNT(*) AS total FROM student;
| active | total |
|---|---|
| 117 | 120 |
Three students left the lists but are still in the table; the total is still 120. If Hiro Kim comes back next term, a single UPDATE ... SET active = TRUE is enough. The cost is clear too: from now on, every query that lists students needs WHERE active; if you forget, inactive students get mixed into reports. That is why the idea that "deleting always means cleaning up" is misleading. Sometimes cleaning up means leaving the row in place and marking it.
You now have four tools: DELETE with a condition, TRUNCATE with no condition, DROP TABLE that removes the table, and the logical delete that leaves the row in place. The choice depends on whether the deleted information will ever be needed again. Match each situation with the right tool:
Which tool fits each situation?
For each row, pick its match from the list, then check.
The same habit applies in every database. An online stationery site has four items in its cart table; items whose quantity has dropped to 0 will be removed from the cart.
Example 6 (outside the case): Deleting zero-quantity items from the cart
CREATE TABLE cart (item VARCHAR(20), quantity INTEGER); INSERT INTO cart VALUES ('notebook', 2), ('pen', 0), ('eraser', 1), ('ruler', 0); DELETE FROM cart WHERE quantity = 0 RETURNING item;
Result (row order may vary):
| item |
|---|
| pen |
| ruler |
The notebook and the eraser remain in the cart. The setup is ready in the cell below. First write a SELECT with the same condition on the last line and see what will be deleted, then change it to DELETE. At the end, remove the line WHERE quantity = 0 and run again: RETURNING shows all four items, and the cart is emptied.
Try it now· not graded; doesn't affect progress
The summary of safe deleting is this: test the condition with SELECT and see the row count, take a backup if needed, delete the dependent rows in the right order, confirm the result with RETURNING or a check query, and do not delete at all if the row's history matters. Each of these steps is a separate command, and if something goes wrong between them, a half-finished change can remain: enrollments deleted but the offering not deleted. In lesson 37 you will learn to put these steps into one transaction and roll back all of them if there is an error. There you will also see how the setup that rolls back every run here is built in real systems with BEGIN, COMMIT, and ROLLBACK.
The condition looks at two tables at once; if neither has a reference, deleting is safe.
DELETE FROM instructor t WHERE NOT EXISTS (SELECT 1 FROM student o WHERE o.advisor_id = t.id) AND NOT EXISTS (SELECT 1 FROM course_offering a WHERE a.instructor_id = t.id) RETURNING id, first_name, last_name;
| id | first_name | last_name |
|---|---|---|
| 18 | Yuki | Cohen |
If the second NOT EXISTS were forgotten, an instructor who teaches but advises no one would be selected, and a course_offering_instructor_id_fkey error would come. Here only instructor 18 meets both conditions.
Enrollments deleted by mistake are put back from the backup table with the INSERT INTO ... SELECT from lesson 34.
deleted_enrollment
* enrollment offering_id = 13;
enrollment offering_id = 13;
enrollment * deleted_enrollment;
( (*) enrollment) enrollment,
( (*) enrollment offering_id = 13) offering_13;Trying to delete the parent row before its children, then removing the constraint or widening the condition to get past the error:
OutputDELETE FROM course_offering WHERE id = 13;
ERROR: update or delete on table "course_offering" violates foreign key constraint "enrollment_offering_id_fkey" on table "enrollment"A foreign key error is a warning: it means data depends on that row. The right fix is to delete the dependent rows on purpose first (DELETE FROM enrollment WHERE offering_id = 13;, then the offering) or not to delete at all and use a logical delete; it is not to remove the constraint.
DELETE FROM table WHERE condition permanently deletes the rows that match the condition; with no WHERE, all rows are deleted without a warning. Run a SELECT with the same WHERE first, see the rows and their count, then change only the command.NOT EXISTS; if the subquery contains NULL, NOT IN silently selects 0 rows.CREATE TABLE ... AS SELECT and see the deleted rows with RETURNING; for records whose history matters, use a logical delete (active = FALSE) instead of deleting.Next lesson: you will learn to group delete, update, and insert into a single transaction and roll them all back if one step goes wrong.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
| enrollment | offering_13 |
|---|---|
| 781 | 2 |
The backup stored all the columns, including id, with SELECT *, so the enrollments came back with their old numbers. Without the backup, there would be no way to bring these two rows back.