UPI Study › Courses › Database Programming › Free lessons › Lesson 6.4 Free with a free account
Removing Records with the DELETE Statement
Database Programming · Chapter 6: Data Retrieval and ModificationSection 6.4 · lesson 38 of 768 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Transaction Control Language (TCL): Managing Data Safely →← Changing Records with the UPDATE StatementNext lesson: Transaction Control Language (TCL): Managing Data Safely →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Deleting rows safely with WHERE, foreign key rules, and soft deletes.
- Write DELETE statements with precise WHERE conditions and correct operator grouping
- Explain how NO ACTION, CASCADE, and SET NULL rules affect deleting a parent row
- Compare hard deletion with a soft-delete flag
- Follow a preview, transaction, and count-check routine before committing a deletion
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (976 words). Read along, or search it.
Opening Question
Removing a Customer Who Still Has Orders
Amina Diallo administers the database at Lantern Books, our fictional bookstore. Someone asks her to remove an old customer record. That sounds simple, until an order still points to the customer. Should the request remove only a row, remove related history, or merely hide the account? We will test those outcomes separately, before deciding what a safe deletion actually requires.
Table Setup
Six Customers With Stable Keys
Our disposable database uses the six canonical customers. Their names, cities, and points are fictional teaching data. The primary key gives each customer a stable identity. Deleting a customer removes the entire row, not just one column. Run the customer setup. No output indicates these creation statements finished quietly; later queries will check the contents.
Referential Integrity
Orders That Reference Their Customers
Now create the canonical orders subset. Each child order carries a customer identifier, referencing its parent customer. The reference is required here. Referential integrity means a non-null foreign key must identify an existing parent; nullable keys can represent no link. Run this setup. Our sandbox omits order items, so orders have no further children here; a real deletion must inspect every dependent level.
Basic Syntax
Deleting One Customer by Identifier
Delete from names the target relation. Where chooses the rows; a unique identifier gives a precise target when the request concerns one customer. Dara has no orders in this baseline. Run the preview and deletion: one customer appears, and one row is removed. Rollback restores Dara here. Once committed, an ordinary rollback cannot recover a deleted row; recovery then requires an appropriate backup or recovery process.
Filter Conditions
Comparisons, Ranges, Lists, and Patterns
Delete accepts familiar conditions: comparisons and between for ranges, or in for a list of identifiers. Like matches text patterns, while is null tests missing values where null is allowed. Not reverses a condition; and and or combine tests. These are reference statements, not approved removal requests. A condition can be valid while selecting records that the business must retain.
Operator Precedence
Parentheses Around Pune or Leeds
Suppose a request selects customers from Pune or Leeds, but only those below one hundred points. Parentheses determine whether that limit applies to both cities. Run the selections. Without grouping, and binds first: every Pune customer qualifies, plus the qualifying Leeds customer. The grouped condition returns only Ben and Farid. Preview identities before turning either selection into a delete; a count cannot explain a misplaced parenthesis.
Missing WHERE
Every Row Removed, Structure Kept
A missing where clause makes every row eligible. This sandbox copy has no foreign keys, so nothing blocks the unrestricted deletion. Run it. Six rows are removed, zero remain, and the empty relation can still be queried. Delete leaves the structure in place. Truncate table is a different operation, with engine-specific transaction and key-counter rules. SQLite lacks that command; drop removes the structure itself.
Foreign Key Block
Deleting a Parent With Orders Fails
Chen has an order, so removing only that parent would orphan a required link. The default immediate no-action rule blocks this attempt. Run it. SQLite reports a foreign-key failure, and the customer is still present. The rejected delete did not remove its children either. Restrict also blocks removal, though timing can differ with deferred constraints. SQL Server uses no action, without a restrict keyword.
Manual Order
Deleting Children Before the Parent
If removal is justified, inspect children first. Asha has two orders; deleting those children before the parent satisfies this sandbox relationship. Run the sequence inside one transaction. The child count is two, and the final delete removes one parent. Rollback restores the whole example. On a database containing order items, handle those deeper children first as well. Never delete sales history merely to silence a foreign-key error.
ON DELETE CASCADE
Children Removed With Their Parent
A separate sandbox relationship uses on delete cascade. Its two child links copy Asha's order identifiers, without changing our canonical schema. Run the parent delete. The direct affected count is one, while zero children remain: SQLite's count does not include those cascading removals. Cascades can travel through several levels, without a separate confirmation. Choose them only when children should truly disappear with their parent.
ON DELETE SET NULL
Orders Kept Without a Customer Link
Here the alternative rule is on delete set null. The child key permits missing values, so the orders can survive without a customer link. Run it. Both child rows remain, with null links displayed explicitly. Requiring the key to be not null would conflict with this intended outcome. The choice belongs in the relationship definition. Decide whether to block, remove children, or detach them, based on the records' meaning.
Soft Delete
Hiding a Row With an Active Flag
A soft delete marks a stored row instead of removing it. This disposable flag extension starts every customer as active. Run the example. Hiding Dara leaves five active customers; clearing the flag restores six. Existing foreign-key links remain valid because the parent still exists. Every normal query must apply the visibility rule. Soft deletion preserves history and stored data; it does not satisfy a requirement to erase that data.
Dialect Comparison
LIMIT, TOP, and Safe-Update Guards
MySQL supports order by with limit for a single-target delete. SQL Server offers top, which alone does not choose the oldest rows. MySQL safe-update mode is a useful guard, with key and limit qualifications. SQL Server has no matching switch; neither habit replaces a precise condition. For important removals, use a tested backup and a copy first. Preview the exact condition, begin a transaction, delete, inspect the count, then commit or roll back.
Quick Check
Deleting One Child Order
A test order for Farid must be removed. The script names only order five thousand six; examine both subsequent queries. What customer count and order count will the two queries print? Pause and predict. One, then zero. Deleting the child order removes that order, while Farid's parent customer remains. A cascade rule acts when its referenced parent is deleted. It does not automatically travel upward from a removed child to erase the parent.
Key Takeaways
Precise Conditions and Checked Dependencies
Delete removes whole rows, while the structure stays. Use a precise condition, and inspect both the preview and affected count. Check every dependency before removing a parent. Amina now knows whether the relationship blocks deletion, removes children, or preserves them with nullable links. Choose hard removal or a soft-delete flag deliberately. Keep recovery available, and finish the transaction only after verifying the result.
About Database Programming at UPI Study
Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Removing Records with the DELETE Statement
What happens when you delete a row that other rows reference with a foreign key?
How do you delete specific rows safely in SQL?
What is a soft delete in a database?
How do you limit how many rows a DELETE removes?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Database Programming.
76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
Updated
3 credits · NCCRSEnroll →