Removing Records with the DELETE Statement, Explained

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

← 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 →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

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.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
The result depends on the foreign key's ON DELETE rule. Under the default NO ACTION rule, or RESTRICT, the database blocks the delete while child rows still reference the parent. ON DELETE CASCADE removes the child rows along with the parent, possibly through several levels of tables. ON DELETE SET NULL keeps the children but sets their foreign key to NULL, which requires a nullable column. SQLite enforces these rules only when foreign key support is switched on.
How do you delete specific rows safely in SQL?
Run a SELECT with the exact condition first, then use that same condition in a DELETE inside a transaction. For example, preview with SELECT * FROM customers WHERE customer_id = 4, run DELETE FROM customers WHERE customer_id = 4, and compare the affected count before committing. Use parentheses when mixing AND with OR. Once committed, a hard delete cannot be undone with ROLLBACK; recovering it needs a backup or another recovery process.
What is a soft delete in a database?
A soft delete hides a row by setting a flag, such as is_active = 0, instead of removing it. History stays available, foreign keys remain valid, and the row can be restored by clearing the flag. The cost is that every normal query must filter with WHERE is_active = 1, or hidden rows reappear. Because the data is kept, a soft delete does not satisfy a request to erase personal information.
How do you limit how many rows a DELETE removes?
MySQL allows ORDER BY and LIMIT on a single-table DELETE, so DELETE FROM orders WHERE status = 'test' ORDER BY order_date LIMIT 10 removes up to ten of the oldest matching rows. SQL Server uses DELETE TOP (10), but that TOP follows no ordering, so to choose specific rows, select their keys with ORDER BY in a subquery or CTE first. The limit only caps the count, while WHERE still decides which rows qualify.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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

Database Programming
3 credits · NCCRS
Enroll →