Dropping Columns and Rows from Tables, Explained

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

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

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

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.

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 Dropping Columns and Rows from Tables

How do you drop a column from a table in SQL?
Use ALTER TABLE with DROP COLUMN, for example ALTER TABLE customers DROP COLUMN fax; which removes the column and its values from every row. To drop two columns, MySQL repeats the clause (DROP COLUMN a, DROP COLUMN b), while SQL Server lists both names after one DROP COLUMN. First check indexes, constraints, views and queries that use the column, and save needed values with the primary key. In MySQL, ALTER TABLE commits implicitly, so ROLLBACK cannot undo it.
How do you safely delete old rows from a SQL table?
Preview the target rows with a SELECT, copy them to an archive table, verify the saved identifiers, then delete exactly those rows inside a transaction. Check the affected row count and the remaining data before COMMIT, because ROLLBACK can undo the delete only until then. A DELETE without a WHERE clause removes every row. Large cleanups often run in smaller committed batches, using DELETE with LIMIT in MySQL or DELETE TOP (n) in SQL Server.
What happens to child rows when you delete a parent row?
It depends on the foreign key's ON DELETE action. CASCADE deletes the children too, so when both links cascade, removing a customer with two orders holding four order items deletes seven rows in total. NO ACTION, or RESTRICT where supported, can refuse to delete a parent that still has children, and SET NULL keeps the children but clears their foreign key, which requires that column to allow NULL. SQL Server offers NO ACTION but not the RESTRICT keyword.
What is a soft delete in SQL?
A soft delete marks a row inactive with a flag instead of removing it, for example UPDATE customers SET is_active = 0 WHERE customer_id = 3; The row keeps its identity and foreign key links, so order history still works and reactivation is easy. The common mistake is forgetting the filter: queries for active records must include WHERE is_active = 1, or inactive rows still appear. Removing personal data still needs its own policy.

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 →