UPI Study › Courses › Database Programming › Free lessons › Lesson 10.1 Free with a free account
Dropping Columns and Rows from Tables
Database Programming · Chapter 10: Table Cleanup and Structural ChangesSection 10.1 · lesson 60 of 769 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: Removing Constraints with SQL DROP Constraint →← Altering Table Structures with SQL CommandsNext lesson: Removing Constraints with SQL DROP Constraint →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Remove columns and rows safely with backups, transactions and dependency checks.
- Drop a column with ALTER TABLE after checking dependencies and saving keyed values
- Preview, archive and delete rows inside a controlled transaction
- Remove duplicate rows with an explicit survivor rule and prevent their return
- Compare cascade deletes, restricting foreign keys and soft deletes
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 (1,083 words). Read along, or search it.
Opening Scenario
A Cleanup Request at Lantern Books
Amina Diallo, the database administrator at Lantern Books, receives a cleanup request: remove unused fax numbers and stale orders. One change removes a field from every customer. Another removes whole records, possibly taking dependent records with them. How can she make the database smaller, while preserving information the bookstore still needs? Our examples use disposable teaching copies.
Sandbox Setup
A Small Customer Projection
Start with a small projection of our shared customers, retaining their canonical identifiers, names, cities, and points. We use SQLite for runnable examples. MySQL and SQL Server differences will appear in labeled listings, without simulated terminal results. Run the setup file against our disposable shop database. Creation and insertion finish quietly; no printed rows are expected.
Worked Example
Save Fax Values, Then Drop the Column
Add an illustrative fax field, then save its values with the stable customer identifier before removing it. Drop column removes that field and its values from the live table. The separate backup can later reconnect values by customer identifier. Run the file. The schema query will find no fax column; the backup query will retrieve Asha's saved number. The result shows the preserved value. This local copy helps recover a field; it does not replace an independently protected database backup.
Dialect Differences
DROP COLUMN in MySQL and SQL Server
The basic drop column syntax also works in MySQL and SQL Server. For multiple columns, MySQL repeats the clause. SQL Server lists the column names after one drop column clause. Its select into syntax creates the keyed backup table. MySQL alter table commits implicitly. SQL Server can roll back this change inside an uncommitted transaction; SQLite can too.
Before You Drop
Check Indexes, Keys, Views and Queries
Before changing structure, inspect dependencies: indexes, foreign keys, defaults, views, reports, and application queries that use the field. MySQL can remove an affected index column and its default automatically. SQL Server commonly blocks the drop until dependent indexes and constraints are removed. Foreign keys can block either server. A non-schema-bound view or application may fail only later, so save data and test consumers after the change.
Second Setup
Orders With an Illustrative Status Field
For cleanup, use three canonical orders with an explicitly added status field. Their identifiers, customer links, and dates stay consistent. The status values are illustrative. Amina wants canceled orders before September fourth, twenty twenty-six, archived before they leave the live table. Run this second setup. The foreign key protects customer links, and the sandbox deliberately omits order items for this first cleanup.
Archive First
Preview and Preserve the Exact Rows
An archive table holds rows we intend to retain outside the live workload. First preview the exact selection, then preserve the same identified records. Here the copy uses one explicit predicate. Compare the saved identifiers and values with the intended set; equal row counts alone cannot prove completeness. Run the archive file. The query will identify the saved orders, and commit will preserve this copy in our sandbox. Coordinate concurrent writers during real cleanup. Otherwise a preview and a later delete may describe different data, even with identical wording.
Controlled Delete
Delete Archived Orders in a Transaction
Delete only the archived identities, inside a transaction. This makes the target set explicit, rather than rerunning a moving date condition. Rows affected reports what the direct deletion changed. Inspect remaining data and dependent rows before deciding whether to commit or roll back. Run the cleanup. We expect the two saved identities to leave the live table, while the new order remains. The output confirms that outcome. A delete without a where clause targets every row; a transaction helps only until its changes are committed.
Large Cleanups
Batches With DELETE LIMIT or TOP
For large cleanups, use manageable batches, with a checked target set and a separate commit for each completed batch. MySQL offers delete limit; SQL Server offers delete top. Those clauses do not automatically choose a chronological order, and SQLite syntax differs. Batching reduces the size of each transaction, but requires restartable bookkeeping. Archiving, verifying, and deleting must stay coordinated across repeated runs.
Finding Duplicates
Preview Repeated Emails With a Self-Join
A separate subscriber sandbox repeats email addresses. The business rule chooses the lowest identifier as survivor, which need not mean earliest creation time. A self-join compares the table with itself. A later candidate matches an equal email with a lower identifier; distinct prevents repeated candidate rows. Run this preview. It prints only the identifiers proposed for removal, without deleting any subscriber yet. Three candidates appear. Subscriber six has two lower matching identifiers, which explains why the preview needed distinct.
Deduplication
Delete Duplicates, Then Add a Unique Index
Apply the same survivor rule to deletion, then add a unique index. The required email column also rules out null identities. SQLite uses an identifier subquery here. MySQL and SQL Server also support an alias-targeted delete from a self-join; that syntax is dialect-specific. Run the cleanup. Existing duplicates must disappear before the unique index can be created successfully. The surviving identifiers are one, two, and four. Prevention now lives in the database, instead of depending on everyone remembering the cleanup rule.
Foreign Key Actions
How Far a Parent Delete Reaches
An order is a child of its customer, and an order item is a child of its order. Inspect every link before deleting a parent. Cascade deletes children too. Asha's two orders contain four item rows. Through cascading links, her deletion would remove seven rows altogether. Restrict, or no action, can refuse the parent deletion. SQL Server uses no action; set null preserves children only where their foreign keys allow null.
Alternative Approach
Soft Delete With an Active Flag
Old but valid history may belong in an archive. Required business records may need to stay available, under the organization's applicable retention policy. A soft delete marks a row inactive, preserving its identity and links. Here we deactivate Chen instead of deleting the customer. Run the update and filtered query. Ordinary active-customer screens must include the flag condition, or inactive customers still appear. Asha and Ben remain visible. Reactivating a flag is easy, but removing personal information requires its own policy and careful review of dependent records.
Quick Check
Predict Ben's Flag After Rollback
A new request temporarily deactivates Ben. The script then rolls back, then inspects Ben's stored flag after Chen's earlier deactivation. Which description fits Ben after the script finishes? Pause, and predict.
Answer Explained
Rollback Restores Ben but Not Chen
Ben remains active. Run the script to test that prediction; the rollback reverses Ben's temporary change. Ben's flag is one. Chen's earlier change was committed separately, so this rollback does not bring Chen back. Inactive would describe keeping Ben's update. An absent row would require deletion; this script only updates a flag and then reverses that update.
Key Takeaways
Clean Up Without Losing Needed History
Amina can retire the fax field after checking dependencies and preserving keyed values. Dropping structure deserves a recovery plan. For rows, preview, archive, verify, then delete within controlled transactions. Resolve duplicates with an explicit survivor rule and prevent their return. Finally, inspect cascade scope and choose deletion, archiving, or inactivity according to the data's purpose. Cleanup succeeds when needed history still works.
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 Dropping Columns and Rows from Tables
How do you drop a column from a table in SQL?
How do you safely delete old rows from a SQL table?
What happens to child rows when you delete a parent row?
What is a soft delete in SQL?
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 →